React Manage REST API State Globally with Context API Tutorial

Last updated on: by Digamber

React Js Handle Rest API data globally with Context and useState hook tutorial. In this comprehensive tutorial, you will learn simple and easy techniques on how to send the REST API data from parent component to child components or in deep components tree in React js application using context hook and useState hook.

Moreover, we will also show you how to install and use the Axios library to make the HTTP Get request to fetch the data response from the server.

We will create the context provider, set the values or data in the context provider and pass the values from the parent or higher-order component to the child components.

Global states are meant to impact on large-scale web applications; seldom do you manage states which are repeated and might be needed in various situations. It is not considered the best policy to write a code repeatedly, and it consumes both memory and time.

How to Handle REST API State Globally in React Js using Context and useState Hook

  • Step 1: Install React App
  • Step 2: Install Bootstrap & Axios Modules
  • Step 3: Create Context File
  • Step 4: Build Context Provider
  • Step 5: Add Provider on Parent Component
  • Step 6: Access Global State in Child Component
  • Step 7: Start React Application

Install React App

First step is to install a brand new React application using the given command.

npx create-react-app react-global-state-rest-api

Next, get into the project folder.

cd react-global-state-rest-api

Install Bootstrap & Axios Modules

Use the following command to install Axios and Bootstrap modules altogether.

You can run the given command to install the packages.

npm install axios bootstrap

Create Context File

Create the contexts/ directory, inside here you have to create a new file and name it ApiContext.js then insert the given code into it.

import { createContext } from 'react'
export const ApiContext = createContext([])

Build Context Provider

Inside the contexts folder, again create a new file you have to name it Store.js and insert the given code into it.

import React, { useState, useEffect } from 'react'
import { ApiContext } from '../contexts/ApiContext'
import axios from 'axios'
function Store({ children }) {
  const [users, setUsers] = useState([])
  useEffect(() => {
    axios
      .get('https://jsonplaceholder.typicode.com/users')
      .then((res) => {
        setUsers(res.data)
      })
      .catch((error) => {
        console.log(error)
      })
  }, [])
  return (
    <ApiContext.Provider value={[users, setUsers]}>
      {children}
    </ApiContext.Provider>
  )
}
export default Store

We imported the ApiContext we will use it to define ApiContext.Provider where we have to pass the data that we have got using the REST API and useState.

Add Provider on Parent Component

To share the data globally or in child components, first import the Store that we created using ApiContext.

Make the Store the parent component this way; all the components defined under this provider will be able to get the global REST API data.

Open the App.js file and insert the following into the file.

import React from 'react'
import 'bootstrap/dist/css/bootstrap.min.css'
import './App.css'
import Users from './components/Users'
import Store from './contexts/Store'
function App() {
  return (
    <div className="container mt-5">
      <Store>
        <Users />
      </Store>
    </div>
  )
}
export default App

Access Global State in Child Component

Create the components directory, then create the Users.js file, make sure to paste the given code into the file.

import React, { useContext, useEffect, useState } from 'react'
import { ApiContext } from '../contexts/ApiContext'
function Users() {
  const [users, setUsers] = useContext(ApiContext)
  useEffect(() => {
    console.log(users)
  }, [users])
  return ( 
    <div>
      <h2 className="mb-4">
        React Handle REST API Global State with Context Hook Example
      </h2>
      {users.map((res, idx) => {
        return (
          <div className="card mb-2" key={idx}>
            <div className="card-body">
              <h5 className="card-title">{res.name}</h5>
              <h6 className="card-subtitle mb-2 text-muted">{res.username}</h6>
              <p className="card-text">{res.company.catchPhrase}</p>
              <a href="#" className="card-link">
                {res.website}
              </a>
            </div>
          </div>
        )
      })}
    </div>
  )
}
export default Users

Import the useContext hook from react library, and import the ApiContext from the context directory. Use the values in the useContext destructuring prop that we defined in the context provider.

The useEffect hook is being used to perform the side effect; as you can see, we passed the users prop in the array symbol because as soon as any change occurs in this value, it will be updated in the Users component.

We are showing the REST API data in the react HTML using Bootstrap that we set globally.

Start React Application

Ultimately, you are ready to run the suggested command for running the application.

npm start

You can see the app on the browser using the given url.

http://localhost:3000

React Manage REST API State Globally with Context API Tutorial

Conclusion

In this guide, you have learned how to share the REST API global state in React components; on top of that, we have also explained how to access the global state in React components.

For that, we retrieve the global state in the child component and display the API response or data in React’s HTML list view using for loop and Bootstrap 5.

Digamber

I am Digamber, a full-stack developer and fitness aficionado. I created this site to bestow my coding experience with newbie programmers. I love to write on JavaScript, ECMAScript, React, Angular, Vue, Laravel.