React useContext Hook

  • Share this:

The `useContext` hook is a way to access the value of a React context from within a functional component. It allows you to consume the context in a declarative way, without having to manually pass the context value through props to every level of the component tree.

Here's an example of how to use the `useContext` hook to consume a context value:

import { useContext } from 'react';

// First, we create a context with a default value
const MyContext = React.createContext('default value');

function MyComponent() {
  // Then, we can use the useContext hook to consume the context value
  const contextValue = useContext(MyContext);

  return <div>{contextValue}</div>;

To provide a context value for a component tree, you can use the `<MyContext.Provider>` component. This component accepts a value prop, which will be used as the `value` for the context. Any components within the provider that consume the context using the `useContext` hook will receive the provided value.

import { MyContext } from './MyContext';

function App() {
  return (
    <MyContext.Provider value="provided value">
      <MyComponent />

In the example above, the `MyComponent` component will receive the value "provided value" for the `MyContext` context.

It's important to note that the `useContext` hook only re-renders a component if the context value changes. This means that if you want to force a re-render of a component that is consuming a context value, you need to change the context value itself.



About author
I am a professional web developer. I love programming and coding, and reading books. I am the founder and CEO of StorialTech.