How to use and implement useContext()

The useContext hook in React is used to access the current value of a React context. It allows a component to consume a value provided by a Context.Provider located higher up in the component tree, without passing props down manually.



Here are the general steps to use useContext:

1- Create a context: First, you need to create a context using the createContext() function.

// Create a context
import React, { createContext } from 'react';

const MonContexte = createContext();

export default MonContexte;


2- Consume the value with useContext: In the child components of Context.Provider, use the useContext hook to access the context's value.

import React, { useContext } from 'react';
import MonContexte from './MonContexte';

const ComposantConsommateur = () => {
  const valeurContexte = useContext(MonContexte);

  return (
    <div>
      <p>Valeur du contexte : {valeurContexte}</p>
    </div>
  );
};

export default ComposantConsommateur;


3-Provide a value with Context.Provider: Use Context.Provider to wrap the part of your application where you want the context to be available. Provide a value to this context.

import React from 'react';
import MonContexte from './MonContexte';
import ComposantConsommateur from './ComposantConsommateur';

const MonComposantPrincipal = () => {
  const valeurFournie = 'Valeur fournie depuis le composant principal';

  return (
    <MonContexte.Provider value={valeurFournie}>
      <div>
        <h1>Composant Principal</h1>
        <ComposantConsommateur />
      </div>
    </MonContexte.Provider>
  );
};

export default MonComposantPrincipal;

Post a Comment

Previous Post Next Post