kentcdodds / ama

Ask me anything!
https://github.com/kentcdodds/ama/issues?q=is%3Aissue+is%3Aclosed
685 stars 75 forks source link

What approach do you prefer to cache data to not call the server every time when useEffect re-render? #846

Closed slim-hmidi closed 3 years ago

slim-hmidi commented 3 years ago

I want to know what is the approach or solution that you recommend when you create a component that needs to call an api to get data to display them later:

import React from 'react';

const UserList = () => {
const [data,setData]=React.useState([]);
const [error,setError]=React.useState('');

useEffect(() => {
  const fetchUsers = async ()=> {
   return fetch.get('url')
      .then(res => res.json)
      .then(data => setData(data))
      .catch(error => setError(error));

}
fetchUsers();
},[]);

if(error) {
 return <span>{error.message}</span>
}

return(
 {data.map(d => (<li key={d.id}>{d.name}</li>))}
)
};

So in order to not fetch the list of the users for e.g in every re-render, do you prefer to use react-query library or use cache and manage things by yourself like implementing Redis to cache the data to be used whenever a new fetch will be executed. What suggestions do you recommend to optimize the performance of the app to reduce useless re-render.

kentcdodds commented 3 years ago

Hi @slim-hmidi,

I'd strongly advise using react-query 👍