useContext hook in react

useContext hook in react

useContext hook in react

The useContext hook is a function that lets you use the value of a given context. It accepts a context object (the value returned from React.createContext) and returns the current context value for that context.


This hook can make it easier to access values from a provider, without having to use a Consumer or wrap components in it.

Here’s an example:

import React, { useContext } from 'react';

// Create a Context
const NumberContext = React.createContext();

// It returns a Provider and a Consumer. 
// In functional component, we can skip the Consumer and use the useContext hook.

function Display() {
  // useContext accepts a context object and returns the current context value.
  const value = useContext(NumberContext);
  return <div>The answer is {value}.</div>;
}

function App() {
  return (
    // Use the Provider to make a value available to all
    // children and grandchildren
    <NumberContext.Provider value={42}>
      <div>
        <Display />
      </div>
    </NumberContext.Provider>
  );
}

export default App;

In this example, a context is created with React.createContext(). Inside the App Component, NumberContext.Provider is used which makes the value available to all children. The Display component uses the useContext hook to get the current context value. The value is 42, which was passed by the Provider.


Share Article:
  • Facebook
  • Instagram
  • LinkedIn
  • Twitter
  • Recent Posts