kentcdodds/ama

Should I use useMemo with dependency Array?

Gapur opened this issue · 3 comments

Gapur commented

Hi Kent.
I am confused to use useMemo when I have dependency "Array".

function Chat({ clients }) {
   const displayClients = useMemo(() => clients => clients.status, [clients]);

   return (
      <div>...{displayClients.map(c => <span>{c.name}</span>)}</div>
   );
};

If I use such that above, useMemo will calc with re-render all the time whether clients are changed or not. So useMemo is not useful at this moment. But When I googled about useMemo or useEffect I saw a lot of examples with dependency "array" like this example. I guess it is not correct. What do you think? Should I use useMemo or useEffect with dependency "array"?
Thanks

i think the reason is the clients is passed by reference not value. So it changes when its parent changes. Maybe you can try this:

function Container(){
    const [clients,setClients] = useState([])

    useEffect(()=>{
        fetchClients(params).then(setClients)
    },[params])

    const displayClients =  useMemo(() => clients.filter(client=>client.status==='online'), [clients]);
    
    return <Chat clients={displayClients}/>
}

function Chat({ clients }) {

    return (
        <div>...{clients.map(c => <span>{c.name}</span>)}</div>
   );
};
Gapur commented

If I have Container and pass data to Chat component. But I filtered data and did some change with useMemo. So When We have re-render we will refilter data again. Should I use useMemo or useEffect with dependency "array"?

If I have Container and pass data to Chat component. But I filtered data and did some change with useMemo. So When We have re-render we will refilter data again. Should I use useMemo or useEffect with dependency "array"?

i think if the fn is a pure function and the params is the same, it won't cause a refilter and the displayClients is just the same value and same reference. This article A Look at the React useMemo Hook says it all.

The side effect should be placed in useEffect with its dependence.

By the way, the state library like rematch/redux provides computed value to solve this problem.