DEV Community

Murat Efe Aras
Murat Efe Aras

Posted on

How to useContext and set value of context in child components in 3 steps

1- Create a Context constant and export it

We will import this constant(const) in all functions which we will be using the context. I will name the file Context.js

//Context.js

import React from "react";
export const Context = React.createContext();
Enter fullscreen mode Exit fullscreen mode

2- In App.js Import and provide the context to all Functional Components

//App.js

import React, { useState } from "react";
import { Context } from "./Context.js";

import ComponentA from "./ComponentA";
import ComponentB from "./ComponentB";

export default function App() {
  const [context, setContext] = useState("default context value");
  return (
    <Context.Provider value={[context, setContext]}>
      <ComponentA />
      <ComponentB />
    </Context.Provider>
  );
}

Enter fullscreen mode Exit fullscreen mode

To do that we do 3 things :)

a- Import the Context we created in 1st step
b- Create a state (via useState) which we will share between components.
c- Wrap components with Context.Provider and pass the state(context) and a function(setContext) to update the state which we created in step b.

3- Consume and set/change value of the context in child components.

//ComponentA.js

import React, { useContext } from "react";
import { Context } from "./Context";

export default function ComponentA() {
  const [context, setContext] = useContext(Context);
  return (
    <div>
      ComponentA:
      <button onClick={() => setContext("New Value")}>
        Change Context Value
      </button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode
//ComponentB.js

import React, { useContext } from "react";
import { Context } from "./Context";

export default function ComponentB() {
  const [context, setContext] = useContext(Context);
  return <div>ComponentB: {context}</div>;
}

Enter fullscreen mode Exit fullscreen mode

To consume and change the value of context:

a- Import Context we created in step 1.
b- Import useContext from "react"
c- Consume value of context via useContext and use it like a state variable (see ComponentB)
d- Change the value via setContext function which we get from useContext (see ComponentA)

Full Code:

Top comments (10)

Collapse
 
subhadippramanik profile image
Subhadip Pramanik • • Edited

That's exactly I was looking for and thanks for explaining it such clearly. I followed the same steps in my react native app. But the problem I see here is when my child screen changes the state, it navigates to parent screen.
As a noob I am sure I am doing something wrong.. but not able to figure out. Could you suggest me where should I look into to figure this out?
My flow is

<Context.Provider>
  <Navigator/>
</Context.Provider>
Enter fullscreen mode Exit fullscreen mode

The Navigator has multiple stacks and one of them changes the value of context.

Collapse
 
aslamiqbal profile image
aslamiqbal •

It saves my life. Greate article.

Collapse
 
thanhdatduong4199 profile image
Dat Duong • • Edited

I tried useState for Map:
const [settingValues, setSettingValues] = React.useState>(() => new Map())

When I try to put [settingValues, setSettingValues] to context provider, I have this error: Type '(Map | Dispatch>>)[]' is missing the following properties from type 'Map': clear, delete, get, has, and 3 more.

Collapse
 
issadarkthing profile image
issadarkthing •

Any idea on how to do this using typescript?

Collapse
 
gtala86 profile image
gtala86 • • Edited

did you find any solution?

Collapse
 
miraitunga profile image
Tungamirai • • Edited

something like this maybe ?createContext<[string, React.Dispatch<React.SetStateAction<string>>]>([null!, () => null!]);

Collapse
 
brauliorivas profile image
Braulio Rivas •

Thank's a lot, saved me a ton of time!!!

Collapse
 
diwakardayal profile image
Diwakar dayal •

thanks a ton !!!

Collapse
 
roger10cassares profile image
roger10cassares •

Hey @efearas ! Many thanks! God bless you man in Jesus Christ the Lord Name!

It works just as I expected.

Awesome job!

Collapse
 
mahanmashoof profile image
Mahan Mashoof •

Thanks! In component B
const context = useContext(Context);
would work as well if we don't intend to set it there, right?