useContext

useContext is a hook in React that allows you to access the value of a context in a functional component. It is a way to pass data through the component tree without having to pass props down manually at every level.

Here is an example of using the useContext hook to access the value of a context in a functional component:

import { useContext } from 'react'

const ThemeContext = React.createContext('light')

function Example() {
  const theme = useContext(ThemeContext)

  return <div style={{ background: theme }}>{theme}</div>
}

In this example, the useContext hook is called with the ThemeContext to access its value. The value of the context is destructured into a theme variable, which is then used to set the background style of the component.

You can use the useContext hook whenever you want to access the value of a context in a functional component. It is a useful way to avoid the “prop drilling” problem that can arise when passing props down through a deeply nested component hierarchy.

To use the useContext hook, you will need to create a context with React.createContext and provide a value for the context. You can then pass the context to the useContext hook in any functional component that needs to access its value.

When to use React useContext() ?

Here are some common use cases where useContext() can be useful:

  1. Global state management: When you need to share global state, such as user authentication information or theme preferences, that needs to be accessed by multiple components throughout an application, you can use useContext() to access the context and update the component’s UI in response to changes in the context value.
  2. Managing complex component hierarchies: When you have a large and complex component hierarchy and you need to pass props through multiple levels, you can use useContext() to pass data directly to the components that need them.
  3. Improving performance: When you need to pass a lot of props through a component tree and you want to improve the performance of your application by reducing the number of re-renders that need to happen, you can use useContext() to access the context value and only re-render the component when the context value changes.
  4. Building reusable components: When you need to share functionality between components that are not directly related in the component tree, you can use useContext() to share state and functionality between these components.
  5. Handling cross-cutting concerns: When you need to handle cross-cutting concerns, such as error handling, that need to be handled in multiple parts of an application, you can use useContext() to manage them in one central place.

It’s important to note that useContext() should be used sparingly, as overusing context can lead to complex and difficult-to-debug code. Before using context, consider if props or state management libraries such as Redux or Mobx might be a better fit for your use case.