React Context: A Visual Guide
React Context eliminates prop drilling. But what exactly is prop drilling, and how does Context help? Let's see:
Prop Drilling
Using Context
What is React Context?
React Context creates a direct channel for data flow, bypassing intermediate components.
A Simple Example
Here's a basic example of Context:
Parent Component
Provides UserContext: βAliceβ
Child Component
I don't use or pass any user-related props.
Grandchild Component
Hello, Alice!
I'm using the UserContext directly, without any props passed through Child.
Try changing the user name in the Parent component. Notice how it updates in the Grandchild component without being passed as a prop through the Child component.
This demonstrates how Context allows data to βtunnelβ through intermediate components.
How to Use React Context
Using React Context involves three main steps:
1. Creating the Context
First, we create a Context object:
import React from "react"; const ThemeContext = React.createContext("light");
2. Providing the Context
Next, we wrap our component tree with a Context Provider:
function App() { return ( <ThemeContext.Provider value="dark"> <Toolbar /> </ThemeContext.Provider> ); }
3. Consuming the Context
Finally, we can use the Context in any nested component:
function ThemedButton() { const theme = React.useContext(ThemeContext); return ( <button className={`btn-${theme}`}>I'm styled by theme context!</button> ); }
A more practical example:
Welcome to light mode!
This illustrates the three main steps of using React Context:
- Creating the Context (ThemeContext)
- Providing the Context (ThemeProvider)
- Consuming the Context (ThemedButton and ThemedContent)
Best Practices
When using React Context, consider:
- Using Context for truly global or deeply nested data
- Splitting unrelated data into separate contexts
- Performance implications for frequently changing data
Tip: The React DevTools extension can help you inspect your Context providers and consumers
Conclusion
React Context is a pretty powerful tool for managing state across your application. When used in the right context (pun absolutely intended), it can help make your code more organized and easier to maintain.
π Happy coding
Resources
Feedback
If you have any questions or suggestions about this guide, feel free to reach out:
- Email: marcoshaber99@gmail.com
- LinkedIn: Marco Haber
- Github: @marcoshaber99