Junior
What is the hook useContext in React?
sobes.tech AI
Answer from AI
useContext is a React hook that allows functional components to subscribe to context updates. It provides a convenient way to access the context value without needing to use HOC (withContext) or render props.
Main advantages:
- Simplified code: Eliminates the need to pass props through multiple levels of components (prop drilling).
- Purity of functional components: Enables using context in functional components, making them more compact and readable.
- Performance: When the context value changes, only components using
useContextwill re-render, not the entire tree branch.
Example usage:
- Creating a context:
// MyContext.js import React from 'react'; const MyContext = React.createContext('Default value'); export default MyContext; - Providing the context:
// App.js import React from 'react'; import MyContext from './MyContext'; import MyComponent from './MyComponent'; function App() { const contextValue = 'Hello, world!'; return ( <MyContext.Provider value={contextValue}> <MyComponent /> </MyContext.Provider> ); } export default App; - Using context in a functional component:
// MyComponent.js import React, { useContext } from 'react'; import MyContext from './MyContext'; function MyComponent() { const contextValue = useContext(MyContext); // Using the useContext hook return ( <div> <p>Context value: {contextValue}</p> </div> ); } export default MyComponent;
Important points:
useContextis tied to a specific context instance created withReact.createContext.- If no corresponding
Provideris found in the component tree,useContextwill return the default value specified when creating the context. - When the context value changes, all components using
useContextwith that context will automatically re-render. - For performance optimization,
React.memooruseMemocan be used to memoize components or context values if the context changes infrequently.