DEV Community

Cover image for useEffect firing twice in React 18

useEffect firing twice in React 18

Shivam Jha on July 30, 2022

Gist Acoording to React 18 Changelog: In the future, React will provide a feature that lets components preserve state between unmounts...
Collapse
 
brense profile image
Rense Bakker

For derived state, its highly recommended to use the useMemo hook.

const filteredItems = useMemo(() => items.filter(item => item.price < 500), [items])
Enter fullscreen mode Exit fullscreen mode

That way you avoid doing expensive array manipulation during each render cycle, even if the items did not change.

Collapse
 
fullstackchris profile image
Chris Frewin • Edited

But the effect is identical if you use useEffect and then set this result to something like a filteredItems state variable. By definition, neither useMemo or useEffect will fire unless items changes (as long as the dependency array remains as just [items]. Granted, going the useEffect way of doing it would introduce a new state variable. But probably for something like this you would want a state variable for it anyway.

Collapse
 
brense profile image
Rense Bakker

What useMemo spits out is a state variable. If you change state in useEffect, you trigger another render cycle with new state. useMemo does not do this, it calculates the derived state in the current render cycle (during render), only if its dependencies have changed. useEffect is for side effects only.

Thread Thread
 
fullstackchris profile image
Chris Frewin

Well, I made an example to finally prove what I mean. You can clearly see by both methods (either useEffect or useMemo) that the component is render twice. So its two ways of doing the exact same thing, exact same 'efficiency', the benefit with useEffect is that you get your statevariable you can use later:

codesandbox.io/s/dreamy-wood-nrvfz...

Thread Thread
 
brense profile image
Rense Bakker

Yea... Because you put the console.log inside the useEffect hook for your useEffect example :B I updated your code example for you, so it's a fair comparison:
codesandbox.io/s/distracted-goldst...

Image description

In the image you can clearly see React 18 mounting the components and doing everything twice and then you can see the 2nd render caused by the useEffect hook updating state.

Really... this rule is not a joke: useEffect is only for side effects and should not be used for derived state, thats what useMemo is for, they didnt add this hook because they were bored. If you refuse to use the useMemo hook, you should STILL not use the useEffect hook for derived state. Just use a plain old javascript variable, it has better performance than triggering a 2nd rerender.

const [someStuff, setSomeStuff] = useState([])
const derivedStuff = someStuff.filter(stuff => stuff.isBetterForPerformance)
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
fullstackchris profile image
Chris Frewin

Ok, I admit that example was stupid since I would anyway probably do that as you mentioned just with JavaScript. Therefore, I still can't see a case you would want to do useMemo anywhere. See the newest example: the "JavaScript" only, as you said, is the most efficient, better than using either useMemo or useEffect:

codesandbox.io/s/festive-chatelet-...

I think the problem is from the beginning that the original useMemo example presented would probably only make sense if the 'derived state' of question actually has dependencies on other state variables, then maybe useMemo affords you some advantage, but the way I see it, when each dependency required for this derived state changes you're going to get a rerender, regardless of if you use useMemo or useEffect. This is why stupid arguments like this are such a waste of time and composition is one of the most important skills of writing good React components.

Thread Thread
 
brense profile image
Rense Bakker

No... there's a real functional difference. Updating state in a useEffect hook triggers another rerender on top of the rerender you were already getting from the state update that caused the dependencies of your useEffect hook to change. It's very important to understand this if you're going to be using React hooks, because otherwise you will run into performance issues and unexpected app behavior down the line. useMemo does not trigger a rerender, regardless of how many dependencies you pass into it.

You can opt for putting the logic to calculate your derived state directly into the render function of your component, however, that too can become a problem, for example if you try to render a lot of components at the same time and all of them have a bunch of junk happening inside their render functions, your app will become slow, to a point where it becomes unusable.

It's not an argument, it's a fact that useMemo works this way. It memoizes expensive calculations, so they dont have to happen on each render if the dependencies did not change.

Collapse
 
shivamjjha profile image
Shivam Jha

The issue is when you call useEffect for this, this will not happen during initial render phase.

State set -> react realizes it needs to fire an effect -> usEffect runs -> state set again (filteredItems) -> re render

So you see this is not very performant.
While if you use useMemo (or just simply calculate result without memo), react can calculate result during render which is more desirable

Collapse
 
shivamjjha profile image
Shivam Jha

Yeah, exactly. AlthoughfilteredItems above is technically not a state variable, but a derived value.

Collapse
 
apperside profile image
Apperside

You say "don't use useEfffect for event handlers" and you are totally right, but unless you are using a primitive html element, the best solution for callbacks and event handlers is not in-lining it, rather than you should use useCallback in that case


`function ParentComponent() {

  const myCallback = useCallback(()=>{
    console.log("callback fired");
  },[]);

  return (
    // ✅ Good: using useCallback for memoizing the callback function
    <button onClick={myCallback}>
      Print Receipt
    </button>
  )

  // ...
}
`
Enter fullscreen mode Exit fullscreen mode
Collapse
 
shivamjjha profile image
Shivam Jha

useCallback does make sense; but only when the function creation is expensive. If you are wrapping a simple function (as in example); it is actually slower that without useCallback. A new hook useEvent is coming into React soon that would solve this problem (no need to pass dependencies): github.com/reactjs/rfcs/blob/useev...

Until then, we should sure not to pre-maturely opt for "optimizations" if you will.
Kent C Dodds has written a great article on this: kentcdodds.com/blog/usememo-and-us...

Collapse
 
apperside profile image
Apperside

Hi,
I have read that article, and is really really cool.
However, I think that useCallback should be used not only when the function creation is expensive: the main purpose of useCallback is to memorize the function, hence it's reference, in order to be able to pass it as a prop to a component without causing it (and all of its childs) to rerender because of a function prop change.

Now, if the callback is used to be passed as a prop to a "native" component (like html button for example), it does not have any child and so it shouldn't cause so much troubles. But, for example, if the callback is to be passed to a component's props, and that component then will pass it to a button component, that function reference change will cause the component that renders the button to re-render all its childs as well