Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store data from API so that it can be accessible in other components

Tags:

reactjs

wp-api

I am doing a project with React.js and Wordpress REST API. All this time I have been using axios to get the data from API whenever the component mounts. This means that every single time I render a component that has to display some data I make an API request. The project is scaling up and I realized that this way of doing things is not the best.

How should I deal with this problem? Should I use Redux? I think Redux is an overkill for this since I will not modify the data, I will only display it. Should I use React Context API?

If any code needed, I will add.

like image 418
Gvidas Pranauskas Avatar asked Nov 07 '25 16:11

Gvidas Pranauskas


1 Answers

I think redux is the best solution to keep your project scalable and well organized, but if you don't want to use it, you can try with context, keep in mind that it means that you must call your api in a high level component.

Here's a sample of your app component with the context definition:

import React, { useState, useEffect } from 'react';
import axios from 'axios';

export const DataContext = React.createContext({})

const App = () => {
  const [apiResponse, setApiResponse] = useState({});

  useEffect(() => {
    axios.get(endPoint).then(response => setApiResponse(response))
  },[]);

  return (
    <DataContext.Provider value={apiResponse}>
      <YourAppContent />
    </DataContext.Provider>
  );
}

export default App

Every time you need to get your API data:

import React, { useContext } from 'react';
import Card from './Card';
import { DataContext } from '../App';

const UserCard = () => {
  const data = useContext(DataContext);
  const { user } = data || {};
  return <Card>{user.fullName}</Card>
}

export default UserCard
like image 154
vlk Avatar answered Nov 09 '25 08:11

vlk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!