Use React Context To Share State
Topic | Source |
---|---|
React | React 16: The Complete Course (incl. React Router 4 & Redux) - Udemy |
React context is an advanced feature in React that allows you to share data between components without the need to pass props manually through every level of the component tree.
What is context
React context provides a way to establish global state that can be accessed by any component within the tree, making it useful for scenarios where you have data or settings that many components need access to.
You create a context using the React.createContext
function. This function returns an object with two components: Provider and Consumer.
The Provider component is used to wrap a portion of your component tree where you want to make the context data available.
It takes a value prop, which can be any JavaScript value (e.g., an object, a string, a function).
The Consumer component is used to access the context data within a component.
It's typically used in a render prop pattern or with the useContext hook to consume the context data.
// Creating a context
const MyContext = React.createContext();
// Using a Provider to make context data available
function App() {
const sharedData = "Hello from Context!";
return (
<MyContext.Provider value={sharedData}>
<ComponentA />
</MyContext.Provider>
);
}
// Consuming context data using a Consumer
function ComponentA() {
return (
<MyContext.Consumer>
{value => <p>{value}</p>}
</MyContext.Consumer>
);
}
useContext
In addition to the Consumer component, React introduced the useContext hook, which simplifies context consumption in functional components.
You can use useContext to access the context value directly within a functional component.
You can have multiple context providers nested within each other. When a component consumes context, it accesses the nearest provider up the tree.
You can provide a default/fallback value for a context using the defaultValue property when creating the context. This value is used when no matching Provider is found up the component tree.
Context updates can trigger re-renders in consuming components, so it's important to use context judiciously and consider performance implications.
Common Use Cases:
React context is often used for managing themes, authentication state, user preferences, and any data or functionality that many components need to access.
In summary, React context is a mechanism for passing data down the component tree without explicit prop drilling. It's a powerful tool for managing global state and sharing data among components efficiently. However, it's typically recommended for more advanced use cases, as overusing context can make the component tree less predictable and harder to maintain.