useContext:
- useContext is a built-in React Hook that allows components to read and subscribe to data (context) from a parent component without manually passing props down through every level.
- The useContext hook in React is primarily used to share global data across a component tree without having to pass props down manually through every level.
- This technique eliminates a common development problem known as prop drilling.
Difference between Prop Drilling vs. useContext:
Working:
- useContext hook consumes values from a React Context, making them accessible to functional components.
- First, create a Context object using React.createContext(), which holds the shared state.
- Use useContext to access the context value in any component that needs it, avoiding prop drilling.
- When the value of the Context updates, all components consuming that context automatically re-render with the new value.
The 3 stages in useContext:
To use context, you need to follow three straightforward steps:
1. Create the Context:
- Create a context object using createContext().
- This acts as the data container.
import { createContext } from 'react';
// Create a context with an optional default value
export const ThemeContext = createContext('light');
2. Provide the Context:
- Wrap the parent component tree with the Context Provider and pass the data into the value prop.
- Any child component inside this provider can now access this data.
import { useState } from 'react';
import { ThemeContext } from './ThemeContext';
import DisplayComponent from './DisplayComponent';
function App() {
const [theme, setTheme] = useState('dark');
return (
// Wrap children and provide the current state value
<ThemeContext.Provider value={theme}>
<DisplayComponent />
</ThemeContext.Provider>
);
}
3. Consume the Context:
- Inside any deeply nested functional component, import the useContext hook and your context object to extract the value directly.
import { useContext } from 'react';
import { ThemeContext } from './ThemeContext';
function DeeplyNestedChild() {
// Grab the value directly from ThemeContext without using props!
const theme = useContext(ThemeContext);
return <div className={`box ${theme}`}>The current theme is {theme}</div>;
}

Top comments (0)