Context API

blog

Global state management refers to the practice of managing and sharing state across multiple components in a React application. As an application grows in complexity, some pieces of state need to be shared between many components, sometimes across deeply nested components. Global state management makes it easier to access and update this shared state without having to pass props down multiple levels (prop drilling)

Problem Statement :

In React JS, after api call, how to navigate to a particular route and at the same time, pass the json response data received from api to be displayed on the new route?

Solution :

Using the Context API in React to manage and pass data between components, especially across routes, involves a few steps. The Context API allows us to create a global state that can be accessed by any component within the Provider, which makes it a great choice for passing data between routes.

Here’s how we can achieve this:


import React, { createContext, useContext, useState } from 'react';
 
const DataContext = createContext();
 
export function DataProvider({ children }) {
  const [data, setData] = useState(null);
 
  return (
    <DataContext.Provider value={{ data, setData }}>
      {children}
    </DataContext.Provider>
  );
}
 
// Custom hook for using context
export function useData() {
  return useContext(DataContext);
}
 
// 2. Wrap Your Application with the Provider
 
// Wrap your application (or the part of it that needs access to the context)
// with the DataProvider in your main component file.
 
// App.js
import React from 'react';
import { BrowserRouter as Router, Route, Routes, useNavigate } from 'react-router-dom';
import { DataProvider } from './DataContext';
import HomePage from './HomePage';
import DetailPage from './DetailPage';
 
function App() {
  return (
    <DataProvider>
      <Router>
        <Routes>
          <Route path="/" element={<HomePage />} />
          <Route path="/details" element={<DetailPage />} />
        </Routes>
      </Router>
    </DataProvider>
  );
}
 
export default App;
 
// 3. Fetch Data and Update Context
 
// In the component where you make the API call, use the context to update the data.
 
// HomePage.js
import React from 'react';
import { useNavigate } from 'react-router-dom';
import { useData } from './DataContext';
 
function HomePage() {
  const { setData } = useData();
  const navigate = useNavigate();
 
  const fetchData = async () => {
    try {
      const response = await fetch('https://api.example.com/data');
      const result = await response.json();
      setData(result); // Update context with the fetched data
      // Navigate to the details page
      navigate('/details');
    } catch (error) {
      console.error('Error fetching data:', error);
    }
  };
 
  return (
    <div>
      <h1>Home Page</h1>
      <button onClick={fetchData}>Fetch Data and Go to Details</button>
    </div>
  );
}
 
export default HomePage;
 
// 4. Access Data from the Context in the Target Route
 
// In the component that will display the data, use the context to access the shared data.
 
// DetailPage.js
import React from 'react';
import { useData } from './DataContext';
 
function DetailPage() {
  const { data } = useData();
 
  if (!data) {
    return <div>No data available</div>;
  }
 
  return (
    <div>
      <h1>Detail Page</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
}
 
export default DetailPage;

Summary :

1. Create a Context: Define a context and provider to manage and share the state.

2. Wrap with Provider: Wrap your application with the context provider.

3. Update Context: Use the context to update the state after an API call.

4. Access Context: Consume the context to access the shared data in any component.

Using the Context API in this way ensures that the state is managed globally and can be accessed across different routes and components.

site-logo