How to use React Context
What is context ?
Context is like global variable that you can access from anywhere without having to parse data on the props component.
When to use context ?
I think if you have some data and the data need to be accessible by many components at different nesting levels.
Let’s try
So we will try to create simple way to using react context, Let’s go!
- Install React
first please install react js with command :
npm i -g create-react-app
2. Create React Project
and then you can create the react project with command :
npx create-react-app project-name
3. Create Context
Oke continue to create simple context
a. create folder user in src folder and create file User.js like this
b. write code in file User.js create variable userContext and put value createContext() import from react like this
c. and then create provider as parent in the same file and the all code in file User.js will looks like this, don’t forget to export UserContext and UserProvider in the last line
4. Call Data Context
oke continue to try call data user context from component
a. create folder sample component “UserAuth”
b. write code in the file index.js in folder UserAuth import useContext from react for get data context and then parse UserContext from file context/User in the useContext, and component UserAuth looks like this
c. and then go to to the file App.js change the code import file UserAuth and don’t forget give the wrapper user provider and file App.js looks like this
and finish you can save all file and run with command
npm run start
we successfully tried to create and use react context, maybe that’s all I can share about react context, I have also shared the source of this tutorial on github thank you.