How to create and use a Context in React?
Here’s a simple step-by-step guide:
1. Create a Context:
import { createContext } from 'react'; const MyContext = createContext(defaultValue);
2. Provide the Context: Wrap a part of your component tree with the Provider.
<MyContext.Provider value={value}> <YourComponent /> </MyContext.Provider>
3. Consume the Context:
- Using
useContext
Hook:
import { useContext } from 'react'; const value = useContext(MyContext);
- Or the traditional way using
Context.Consumer
(older method):
<MyContext.Consumer> {value => <div>{value}</div>} </MyContext.Consumer>
Summary Flow:
- Create → Provide → Consume