React Context is a powerful feature that allows you to manage and share state across your application without the need for prop drilling.
It's particularly useful for passing data, such as themes or authentication, to deeply nested components.
In this quick guide, we'll explore React Context and provide code snippets that seasoned developers can easily follow and implement.
1. Creating a Context
First, you need to create a context using
React.createContext
.This function returns an object with two components:
Provider
and Consumer
.import React from 'react'; const MyContext = React.createContext(); export default MyContext;
2. Providing Context
Wrap your application (or a part of it) with the
Provider
component to make the context available to nested components.import React from 'react'; import MyContext from './MyContext'; // Import the context function App() { return ( <MyContext.Provider value={{ theme: 'light', toggleTheme: () => {} }}> {/* Your components */} </MyContext.Provider> ); } export default App;
3. Consuming Context
To access the context's data in a component, use the
useContext
hook.import React, { useContext } from 'react'; import MyContext from './MyContext'; // Import the context function MyComponent() { const context = useContext(MyContext); return ( <div> <p>Theme: {context.theme}</p> <button onClick={context.toggleTheme}>Toggle Theme</button> </div> ); }
4. Providing and Consuming Context in Separate Files
To keep your code organized, you can create separate files for providing and consuming context.
MyContext.js
(Providing Context)import React from 'react'; const MyContext = React.createContext(); function MyContextProvider({ children }) { // Your context data and functions const contextData = { theme: 'light', toggleTheme: () => {} }; return ( <MyContext.Provider value={contextData}> {children} </MyContext.Provider> ); } export { MyContext, MyContextProvider };
MyComponent.js
(Consuming Context)import React, { useContext } from 'react'; import { MyContext } from './MyContext'; // Import the context function MyComponent() { const context = useContext(MyContext); return ( <div> <p>Theme: {context.theme}</p> <button onClick={context.toggleTheme}>Toggle Theme</button> </div> ); }
5. Context with Class Components
You can also use context with class components using the
contextType
property.import React from 'react'; import MyContext from './MyContext'; // Import the context class MyComponent extends React.Component { static contextType = MyContext; render() { const { theme, toggleTheme } = this.context; return ( <div> <p>Theme: {theme}</p> <button onClick={toggleTheme}>Toggle Theme</button> </div> ); } }
And that's it! You've now learned the basics of React Context.
These code snippets can be easily copied and pasted into your projects, allowing you to harness the power of React Context for managing global state and passing data between components in a clean and efficient way.
Happy coding!