Deprecated: Creation of dynamic property Google\Site_Kit\Core\Authentication\Setup::$proxy_support_link_url is deprecated in /home/jtseng7273/public_html/myehouse.com/wp-content/plugins/google-site-kit/includes/Core/Authentication/Setup.php on line 94

Deprecated: Creation of dynamic property Google\Site_Kit\Modules\AdSense\Web_Tag::$module_slug is deprecated in /home/jtseng7273/public_html/myehouse.com/wp-content/plugins/google-site-kit/includes/Core/Modules/Tags/Module_Tag.php on line 42

Deprecated: Creation of dynamic property Google\Site_Kit\Modules\Analytics\Web_Tag::$module_slug is deprecated in /home/jtseng7273/public_html/myehouse.com/wp-content/plugins/google-site-kit/includes/Core/Modules/Tags/Module_Tag.php on line 42

Deprecated: Creation of dynamic property Google\Site_Kit\Modules\Analytics_4\Web_Tag::$module_slug is deprecated in /home/jtseng7273/public_html/myehouse.com/wp-content/plugins/google-site-kit/includes/Core/Modules/Tags/Module_Tag.php on line 42
About React useContext Hook, Part I - Coder Blogger

About React useContext Hook, Part I

React Hooks

In React, the useContext hook is used for consuming context that has been created by a parent component. Context allows you to pass data down the component tree without having to pass props down every level. The useContext hook allows functional components to access the context data without having to use a higher-order component or render prop.

The useContext hook takes a context object as its argument and returns the current value of that context. The context object is created using the createContext function, which creates a new context object with a Provider component and a Consumer component. The Provider component is used to wrap the parent component and pass the context data down to its children.

Here’s an example of how to use the useContext hook:

import React, { useContext } from 'react';

const ThemeContext = React.createContext('light');

function ThemeButton() {
  const theme = useContext(ThemeContext);
  return (
    <button style={{ background: theme === 'dark' ? 'black' : 'white', color: theme === 'dark' ? 'white' : 'black' }}>
      {theme === 'dark' ? 'Dark' : 'Light'} Theme
    </button>
  );
}

function App() {
  return (
    <div>
      <ThemeContext.Provider value="light">
        <ThemeButton />
      </ThemeContext.Provider>
      <ThemeContext.Provider value="dark">
        <ThemeButton />
      </ThemeContext.Provider>
    </div>
  );
}

In this example, the ThemeContext object is created using the createContext function with a default value of ‘light’. The ThemeButton component uses the useContext hook to access the current value of the ThemeContext object and render a button with a light or dark theme based on the current value. The App component wraps the ThemeButton component with two ThemeContext.Provider components with different values, which allows the button to switch between light and dark themes.

Common mistakes when using useContext include not passing the correct context object to the useContext hook, or not wrapping the parent component with the appropriate Provider component. It’s important to ensure that the useContext hook is receiving the correct context object, and that the context data is being passed down through the component tree using the Provider component.

Another trick when using useContext is to create multiple context objects to organize your data more effectively. For example, you might create a UserContext object and a ThemeContext object to separate user data from styling data.

import React, { useContext } from 'react';

const UserContext = React.createContext();
const ThemeContext = React.createContext('light');

function Header() {
  const user = useContext(UserContext);
  const theme = useContext(ThemeContext);
  return (
    <header style={{ background: theme === 'dark' ? 'black' : 'white', color: theme === 'dark' ? 'white' : 'black' }}>
      <h1>Welcome, {user.name}!</h1>
    </header>
  );
}

function App() {
  const user = { name: 'John' };
  return (
    <div>
      <UserContext.Provider value={user}>
        <ThemeContext.Provider value="light">
          <Header />
        </ThemeContext.Provider>
      </UserContext.Provider>
      <UserContext.Provider value={user}>
        <ThemeContext.Provider value="dark">
          <Header />
        </ThemeContext.Provider>
      </UserContext.Provider>
    </div>
  );
}

In this example, the Header component uses both the UserContext and ThemeContext objects to render a personalized header with a light or dark theme. The App component wraps the Header component with two sets of Provider components, one for each theme, and passes the user object down through the UserContext object.

Overall, the useContext hook is a powerful tool for organizing and accessing context data in React functional components. It provides a simple and concise way to consume context without the need for higher-order components or render props. However, it’s important to be mindful of common mistakes such as passing the wrong context object or failing to wrap the parent component with the appropriate Provider component.

Another trick when using useContext is to combine it with other hooks, such as useState or useEffect, to create more complex functionality. For example, you might use useContext to access a theme object and useState to create a toggle button that switches between light and dark themes:

import React, { useContext, useState } from 'react';

const ThemeContext = React.createContext('light');

function ThemeButton() {
  const [theme, setTheme] = useState(useContext(ThemeContext));
  const toggleTheme = () => setTheme(theme === 'dark' ? 'light' : 'dark');
  return (
    <button style={{ background: theme === 'dark' ? 'black' : 'white', color: theme === 'dark' ? 'white' : 'black' }} onClick={toggleTheme}>
      {theme === 'dark' ? 'Dark' : 'Light'} Theme
    </button>
  );
}

function App() {
  return (
    <div>
      <ThemeContext.Provider value="light">
        <ThemeButton />
      </ThemeContext.Provider>
    </div>
  );
}

In this example, the ThemeButton component uses the useState hook to create a state variable for the current theme, and a toggleTheme function to switch between light and dark themes. The initial value of the theme variable is set using the useContext hook to access the current value of the ThemeContext object. When the button is clicked, the toggleTheme function is called to update the state variable and re-render the component with the new theme.

In conclusion, the useContext hook is a useful tool for consuming context data in React functional components. It provides a simple and concise way to access context without the need for higher-order components or render props. By being mindful of common mistakes and combining it with other hooks, you can create more complex functionality and organize your data more effectively.

We’ll explore useContext further in an upcoming article. Look up for a part 2 on useContext.

You Might Also Like