Today I will explain about the useContext hook in react which helps avoid prop drilling(reusing of state variables in deeply nested components).
useContext is a React Hook that allows us to access values from a React Context directly inside your functional components. It’s part of React’s strategy to simplify state sharing across deeply nested components.
The main uses of this are:
Avoids Prop Drilling: No need to pass props through multiple layers.
Centralized State: Ideal for global data like themes, user authentication, or language settings.
Cleaner Code: Makes our component tree easier to manage and read.
Syntax:
import { createContext } from 'react';
const ThemeContext = createContext('light'); // 'light' is the default value
Wrap our app component in provider and give value
<ThemeContext.Provider value="dark">
<App />
</ThemeContext.Provider>
import { useContext } from 'react';
function Button() {
const theme = useContext(ThemeContext);
return <button className={theme}>Click me</button>;
}
When the value passed to the Provider changes, all components using useContext will re-render automatically with the new value.
This is the way useContext works and this is very useful in the real world applications.
Top comments (0)