Q1. What is the useContext hook?
It accepts a context object (created by
It simplifies accessing context without using a Consumer component.
useContext is a React hook that allows you to consume values from a Context object.It accepts a context object (created by
React.createContext) and returns the current context value.It simplifies accessing context without using a Consumer component.
Q2. How do you use useContext?
First, create a context:
Then, provide a value using
In a child, call
Now
const MyContext = React.createContext().Then, provide a value using
<MyContext.Provider value={someValue}> higher in the tree.In a child, call
const value = useContext(MyContext).Now
value equals someValue.Q3. What are the benefits of useContext?
It avoids prop drilling by making data available to any component in the tree without passing props manually.
It's simpler than using Context.Consumer and works seamlessly with functional components.
It's simpler than using Context.Consumer and works seamlessly with functional components.
Q4. When should you use useContext?
Use it for global data like themes, user authentication, language preferences, or UI state that many components need.
For complex state, you might combine it with useReducer.
For complex state, you might combine it with useReducer.
Q5. Can you use multiple contexts with useContext?
Yes, you can call
For example:
useContext multiple times for different contexts.For example:
const theme = useContext(ThemeContext); const user = useContext(UserContext);