How can I reuse the API data for all the pages in react js

Viewed 2238

I'm a newbie in react js. I am building a 4-5 pages website using react js. In all the pages, there is an API called category. What is the best way to request this API once and use the same data for all pages where needed? I tried to find on google but did not come to a satisfactory result so your guide will help to save the client resource to call the same API for every component or pages again and again.

thanks a lot!!!

3 Answers

The answer to this question depends on what scope of resistance you want. If you want to redo the API call every reload, then you can use something like Redux to share the output across multiple components. If you want it to be stored for longer, you can use LocalStorage. Do note that you can also use LocalStorage if you want to only store temporarily, but you need to add code so that you get data from the API during application load.

For better handling fetch data and caching it for next use , you can easily use two powerful library

react-query https://www.npmjs.com/package/react-query

Or

swr https://swr.vercel.app/

They can manage your fetched data and store it for you, in next use if they have your data it return cached instance of your data

Update :

If you want to save your data after reloading page you can use two useful library that can save your state to localStorage

for simple states yo can use :

use-persisted-state https://www.npmjs.com/package/use-persisted-state

and for complex state can use :

use-persisted-reducer

https://github.com/khakestani/use-persisted-reducer

https://www.npmjs.com/package/use-persisted-reducer

There could be two ways I can think of -

  1. Use higher Order Components or Render Props pattern. This will extract the API call logic into a single place and then you can wrap your components to get the data. For more, you can dig in docs https://reactjs.org/docs/higher-order-components.html

  2. Use Redux and thunk to leverage store and actions. you can find redux docs over here https://redux.js.org

Related