Home > Enterprise >  react-table: do I need memoize data even when fetching data with a useEffect hook?
react-table: do I need memoize data even when fetching data with a useEffect hook?

Time:09-03

In the react-table docs examples, the input data to the table is memoized for the following reason:

React Table relies on memoization to determine when state and side effects should update or be calculated. This means that every option you pass to useTable should be memoized either via React.useMemo (for objects) or React.useCallback (for functions).

All their examples use locally defined javascript objects. If I were to fetch data from a server in a useEffect hook, and add it to the component's state, do I still need to memoize it with useMemo? If so, should this memoization take place within or outside useEffect? I'm still wrapping my head around these React hooks and when/if they should be used together.

CodePudding user response:

The reason for using useMemo or useCallback is optimization

So, if you fetch data from a server in an optimized useEffect, let's say it only runs after the initial render, and put the result inside a state via useState, then you do not need useMemo to memoized the state anymore even if there is a heavyCalculation inside it. Why? because the heavyCalculation (if any) will only run once and the state will never change, so it will never affect the react-table performance.

const URL = 'https://for.example.only'

function heavyCalculation(data) {
  ...
}

function Example() {
   const [data, setData] = useState([]);

   useEffect(() => {
     try {
        const res = await fetch(URL);
        const fetchedData = await res.json();
        const updatedData = heavyCalculation(fetchedData);
        setData(updatedData);
     } catch (error) {
        console.log(error);
     }
   },[])
   ...
}

You can see another example here.

  • Related