Sobes.tech
Junior

What is the purpose of the useContext hook in React?

sobes.tech AI

Answer from AI

The useContext hook provides a way to access the value of a React context in functional components without using the consumer component (Consumer). It simplifies accessing data propagated through the component tree, such as themes or localization parameters.

Main advantages:

  • Simplified code: Eliminates the need for render props to access context.
  • Cleanliness: Makes functional components more concise and readable.
  • Convenience: Easy to use within functional components.

Example of usage:

  1. Creating a context:

    // ThemeContext.js
    import { createContext } from 'react';
    
    const ThemeContext = createContext('light'); // Default value
    
    export default ThemeContext;
    
  2. Providing the context:

    // App.js
    import React from 'react';
    import ThemeContext from './ThemeContext';
    import MyComponent from './MyComponent';
    
    function App() {
      const theme = 'dark';
    
      return (
        // Providing the theme value to all child components
        <ThemeContext.Provider value={theme}>
          <MyComponent />
        </ThemeContext.Provider>
      );
    }
    
    export default App;
    
  3. Using the context with useContext:

    // MyComponent.js
    import React, { useContext } from 'react';
    import ThemeContext from './ThemeContext';
    
    function MyComponent() {
      // Getting the current context value
      const currentTheme = useContext(ThemeContext);
    
      return (
        <div>
          Current theme: {currentTheme}
        </div>
      );
    }
    
    export default MyComponent;
    

Thus, useContext is a powerful tool for managing state and data that need to be accessible to many components in an application, simplifying their propagation and usage.