React UseContext is Simple

In Parent component or App.js, we just need to create & export the context, literally by using the createContext hooks! Simply use these few lines of code:

// in App.js
import createContext from 'react';
export const contextToPassDown = createContext();

Then wrap the context Provider over the child components you wish to provide the context

   <contextToPassDown.Provider value=dataToPassDown>
        <ChildComponent />

Then in any Child components that are wrapped by the tag, we just need to use the useContext hooks!

// in ChildComponent.js
import useContext from 'react';
import contextToPassDown from App.js;

const ChildComponent=()=>
  const contextToUse = useContext(contextToPassDown);

  return (<div> contextToUse.username </div>);

export default ChildComponent;

The use cases for useContext are usually:

  1. To Pass down logged-in user info to authorized components
  2. For ‘light’ or ‘dark’ theme

You may practice using this link to: codesandbox

Source link