DEV Community

Yasin
Yasin

Posted on

A quick start to using or context (global state) in react

Before even using global state make sure it's a state that majority of your app is gonna use. If it's just for 2 components for example, you'd just want to use state at the parent level. Then pass it down to the child component as a prop.

If you find yourself making redundant states, that's a good sign that you should use global state. First Thing to do is make a file and call it whatever you want it to be. I had mine in a folder called context because I had more than one global state and I named it "globalPost.js".

Make and name the file

Next import React, useState, and if you are fetching from another place useEffect.

Import the hooks you need

After that create and name the context of your context. Outside of your provider function. Then create your provider function and pass down children as a prop.

create the context and provider

Then inside the provider function name the state whatever you it to be. In my case I am calling it posts and setting it equal to an empty area. Then using useEffect open first mounting to fetch my post data and setting my posts state to the data I just fetched.

Make and set the state

Now in the return of the provider function render .provider on your context that you just made and set the value equal to the state that you want to use in other components. Also in between the context provider in curly brackets call children. Then export your context and your provider.

Render and export context and provider

Import your provider to the highest level component you need it at. So if you need it throughout the entire app render it in the index.js file.

Import provider to highest level component

Lastly you can use it on any component throughout the entire app by importing useContext, and then import your context. Then calling it inside your function component.

Import context in component that needs ir

Top comments (0)