What is React context and how do you use it?
React context provides a way to pass data through the component tree without having to pass props down manually at every level. It is designed to share data that can be considered 'global' for a tree of React components, such as the current authenticated user, theme, or preferred language.
How to Create and Use React Context
-
Create a Context: Use
React.createContext()
to create a context object. The context object comes with a Provider and a Consumer, but in modern React, theuseContext
hook is often used instead of the Consumer.import React from 'react'; const ThemeContext = React.createContext('light');
-
Provide Context: Use a Provider to make the context value available to all children components.
function App() { return ( <ThemeContext.Provider value="dark"> <Toolbar /> </ThemeContext.Provider> ); }
-
Consume Context: Access the context value using the
useContext
hook.import React, { useContext } from 'react'; function Toolbar() { const theme = useContext(ThemeContext); return <div style={{ background: theme === 'dark' ? '#333' : '#FFF' }}>Toolbar</div>; }
Benefits of Using React Context
- Efficiency: Avoids prop drilling, making it easier to manage states that need to be accessed by many components.
- Clarity: Context can make your app's structure more intuitive by grouping related values.
Considerations
While context is powerful, it should be used sparingly as it can make component reuse more complex. For small to medium-sized applications, it works well, but for more extensive state management, libraries like Redux might be more suitable.