Sourcegraphlabs
Get Cody

Welcome to the LLM Litmus Test

Compare and find out which LLM works best for your AI coding cases.

Toggle Cody Context to see how Sourcegraph's Cody Context can improve your answers.

This is an LLM comparison between:

Claude 2.1

vs

Claude 3 Opus

Claude 2.1
tell me how to use react useContext

Here is how to use the React useContext hook to consume and update context values:

1// Create the context 2const MyContext = React.createContext(defaultValue); 3 4// Create a provider to hold the context value 5<MyContext.Provider value={contextValue}> 6 <ChildComponents /> 7</MyContext.Provider> 8 9// Consume the context in a child component 10import { useContext } from 'react'; 11 12function ChildComponent() { 13 const contextValue = useContext(MyContext); 14 15 return <div>{contextValue}</div>; 16} 17 18// Update the context from a child component 19import { useContext } from 'react'; 20 21function ChildComponent() { 22 const context = useContext(MyContext); 23 const [value, setValue] = useState(context); 24 25 const handleChange = () => { 26 setValue('new value'); 27 } 28 29 return ( 30 <div> 31 <button onClick={handleChange}>Change Context</button> 32 </div> 33 ); 34}

The key points:

  • Create context with React.createContext
  • Provide value to context using MyContext.Provider
  • Consume in child with useContext(MyContext)
  • Update by calling state update function returned from useState

Let me know if you need any clarification or have additional questions!

Claude 3 Opus
tell me how to use react useContext

Sure! Here's a concise explanation of how to use the useContext hook in React:

  1. Create a context using the createContext function:
1const MyContext = React.createContext();
  1. Provide the context value using the Provider component:
1function App() { 2 const contextValue = { /* some value */ }; 3 return ( 4 <MyContext.Provider value={contextValue}> 5 {/* child components */} 6 </MyContext.Provider> 7 ); 8}
  1. Consume the context value in a child component using the useContext hook:
1function ChildComponent() { 2 const contextValue = useContext(MyContext); 3 // use the context value 4}

That's it! The useContext hook allows you to access the value provided by the nearest Provider component up the component tree.

A few additional notes:

  • The createContext function takes an optional default value as an argument.
  • The Provider component accepts a value prop, which is the value that will be passed down to consuming components.
  • The useContext hook takes the context object as an argument and returns the current context value.

By using useContext, you can avoid prop drilling and make it easier to share data between components without explicitly passing props down the component tree.