Imagine we are building a website with a dark mode feature. Multiple components may need to know whether dark mode is enabled or disabled.
One way to share this data is through props . But passing props through many components can become difficult.
React provides a hook called useContext to solve this problem.
1. What is useContext?
useContext is a React Hook that allows us to access shared data from different components without passing props manually through every level.
In simple words, useContext helps components share data easily.
2. Why do we need useContext?
Let's understand with an example.
Imagine we have three components:
App
Profile
User
The App component has a username that the User component needs.
We can pass the username through props:
function App () { const username = " Lokesh " ;
return < Profile username = { username } />; }
function Profile ({ username }) { return < User username = { username } />; }
function User ({ username }) { return < h2 > Hello, { username } </ h2 >;…