Search code examples
reactjsasynchronousreact-hooksmemoizationreact-table

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


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.


Solution

  • 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(() => {
         const fetchData = async () => {
           try {
             const response = await fetch(URL);
             const responseJson = await response.json();
    
             if (!response.ok) {
               throw new Error(responseJson.status_message);
             }
    
             const updatedData = heavyCalculation(responseJson);
             setData(updatedData);
           } catch (error) {
             console.log(error);
           }
         }
         fetchData();
       },[])
       ...
    }
    

    You can see another example here.