OneCompiler

How to use Context API in React

344


React context API is the official state management solution by React. In this post, we will see how to add the react context API to our project.

What is context API?

In modern web applications we need the state to be shared across all the components, we can use props to share the data between two components but this process gets complicated when the two components doesn't relate directly. To avoid this problem react introduced context API. It is a global state management solution. We also have some other popular state management libraries like Redux, Mobx etc.

Usage

First, create a file named CanvasContext.js (you can use whatever you wish, UserContext.js if you wish to store the user state) and add the following code.

import React, { useState, createContext } from 'react'
export const CanvasContext = createContext()
export const CanvasProvider = (props) => {
    const [canvas, setCanvas] = useState([])
    return (
        <CanvasContext.Provider value={[canvas, setCanvas]}>
            {props.children}
        </CanvasContext.Provider>
    )
}

We created a context and we created a provider which has an empty list as the state, we shared the context to all children.
Now, go to the root file App.js and wrap all the code inside the provider

import React from 'react';
import Images from './Images';
import './App.css'
import Canvas from './Canvas';
import { CanvasProvider } from './CanvasContext'; //import the context
function App() {
  return (
    <CanvasProvider>
      <div className="main-box">
        <Images />
        <Canvas />
      </div>
    </CanvasProvider>
  );
}
export default App;

Using the context in components

To use the global state inside the components, import the context to that component and use the code below

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

you now have the global state inside your component.

Updating the global state

To update the global state you can simply use the setCanvas method inside your component