Sobes.tech
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 useContext will re-render, not the entire tree branch.

Example usage:

  1. Creating a context:
    // MyContext.js
    import React from 'react';
    
    const MyContext = React.createContext('Default value');
    
    export default MyContext;
    
  2. 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;
    
  3. 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:

  • useContext is tied to a specific context instance created with React.createContext.
  • If no corresponding Provider is found in the component tree, useContext will return the default value specified when creating the context.
  • When the context value changes, all components using useContext with that context will automatically re-render.
  • For performance optimization, React.memo or useMemo can be used to memoize components or context values if the context changes infrequently.