Q1. What is the useContext hook?
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: const MyContext = React.createContext(). Then, provide a value using 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.
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.
Q5. Can you use multiple contexts with useContext?
Yes, you can call useContext multiple times for different contexts. For example: const theme = useContext(ThemeContext); const user = useContext(UserContext);
Q1. What is the useContext hook?
useContext is a hook that consumes a context value. It accepts a context object and returns the current context value. It's an alternative to Context.Consumer and is simpler in functional components.
Q2. How do you use useContext?
First, create a context. Then, in a child component, call const value = useContext(MyContext). This value will be the nearest Provider's value or the defaultValue.
Q3. Can you use useContext multiple times?
Yes, you can call useContext for different contexts to get multiple values. For example: const theme = useContext(ThemeContext); const user = useContext(UserContext);
Q4. What are the benefits of useContext over Consumer?
useContext is more readable and avoids nesting. It also works seamlessly with other hooks. It makes the code cleaner, especially when consuming multiple contexts.
Q5. Does useContext trigger re-renders?
Yes, whenever the context value changes, the component using useContext will re-render. This is how context provides reactivity.
