Home > Net >  Difference and use cases with useEffect and useMemo hooks on React
Difference and use cases with useEffect and useMemo hooks on React

Time:03-29

This is a performance question since both ways are working.

I need to update a value according to the existence of another value. So I did the follow:

const value = useMemo(() => (a ? valueB : valueC), [a]);

This is ok and works but I read that the useMemo hook is not recommended for easy functions, so I changed to:

const [value, setValue] = useState()

useEffect(()=> {
   a ? setValue(valueB) : setValue(valueC)
}, [a])

What is the more performant way to do that and why? Thanks a lot in advance!

CodePudding user response:

The recommendations are avoid useMemo without heavy functions to process... in this case in specific, i think you dont need that... Since you can just create a new variable and attach the value to her, without effects or state.

const value = a ? valueB : valueC;

But if this will be a initial value for something greater, with state manipulations which causes rerender, you can just initialize your state with this incoming prop

const [value, setValue] = useState(a ? valueB : valueC);

CodePudding user response:

It really depends. If your component has many nested HTML elements or components, useMemo is a good choice, since other wise all of your components get re-rendered, cause a state has changed. If not, I think it would be good to prevent React to do all the comparaison stuff, and just trigger a re-render using a state.

Memoization is not free. You could check this YouTube video to learn more about it.

CodePudding user response:

Difference is that useMemo returns value(either cached result or calculated-just-moment-ago) and this value we use to compose result JSX.

Version with useEffect will call setter for useState which will cause another re-render with new value. 2 re-renders instead of 1.

I read that the useMemo hook is not recommended for easy functions

suggests to use normal calculation each time:

const value = a ? valueB : valueC;

rather using useEffect

  • Related