r/reactjs • • Oct 13 '20

Resource Stop useEffect from running on every render with useCallback

https://maxrozen.com/stop-useeffect-running-every-render-with-usecallback/
8 Upvotes

34 comments sorted by

68

u/flyingtortoise88 Oct 13 '20 edited Oct 13 '20

~~This article is INCORRECT! I really wish more people would at least have someone review articles like this before posting.

The example shows the result of calling getUrl being passed down as a prop. This is just a string and will be equal across renders, assuming the id doesn't change.

If the getUrl function itself was passed down as a prop, then useCallback should be used.~~

EDIT: article has been corrected now

3

u/rozenmd Oct 13 '20

Apologies, that's on me for hitting publish late at night instead of re-reading in the morning.

As alluded to lower in this thread, I was using getUrl as the useEffect dependency and then passed the result, rather than the function.

I've since edited the article.

11

u/dcgog Oct 13 '20

Why not set url with a useMemo? This seems like a roundabout way to do it

38

u/grumd Oct 13 '20 edited Oct 13 '20

I don't even see why you would need that. A url is a string, if two strings are equal, but recreated every render, they're still strictly equal (===). That effect should have never been even called twice.

Actually, this article is complete bullshit. I just created a codesandbox to prove that useEffect will NOT be called every render when your dependency is just a URL string (assuming the URL itself doesn't change).

https://codesandbox.io/s/react-playground-forked-djkox

Stupid articles like this is what propagates not understanding basic React and JS principles.

Edit: Most likely Max Rozen was using getUrl as the useEffect dependency and then forgot about it when writing the article. Yeah, you're not supposed to use functions that are created every render as a dependency, because it's a new instance every time. Using primitives as dependencies when possible is the real answer instead of band-aiding everything with useCallback and useMemo.

Edit 2: I don't know why I'm so angry but the way his article starts just infuriates me: "If you’ve done much searching to try understand why your useEffect runs on every render..." -- honestly, who even needs to google stuff like that? If one just knew how useEffect works by reading 10 lines of React docs, one wouldn't have had these basic questions...

Edit 3: If Max is reading this, Max, I'm sorry for being so harsh in this comment. But your article is mistaking people, I'd edit or rewrite it.

2

u/rozenmd Oct 13 '20

Edit: Most likely Max Rozen was using getUrl as the useEffect dependency and then forgot about it when writing the article. Yeah, you're not supposed to use functions that are created every render as a dependency, because it's a new instance every time. Using primitives as dependencies when possible is the real answer instead of band-aiding everything with useCallback and useMemo.

Bingo.

Edit 2: I don't know why I'm so angry but the way his article starts just infuriates me: "If you’ve done much searching to try understand why your useEffect runs on every render..." -- honestly, who even needs to google stuff like that? If one just knew how useEffect works by reading 10 lines of React docs, one wouldn't have had these basic questions...

Surprisingly more people than you'd think, hence the article.

Edit 3: If Max is reading this, Max, I'm sorry for being so harsh in this comment. But your article is mistaking people, I'd edit or rewrite it.

That's what I get for publishing late at night, no worries, editing.

5

u/dcgog Oct 13 '20

Yeah you're totally right. I was assuming the example was a bit contrived and so assuming there's a bit more heavy lifting going on in getUrl you'd want to use the useMemo hook. But yeah if it's literally just a string you should just assign it to a variable and move on.

EDIT: but yeah I see what you're saying. Since url is a primitive value as long as the value is the same the child component won't rerender, regardless of what hook or lack thereof in the parent.

2

u/grumd Oct 13 '20

Just a correction - the child component will rerender anyway. Child components rerender when parent rerenders by default, doesn't matter if props changed or not. Child components will not rerender if they have React.memo applied though.

But as long as the primitive is the same in the list of dependencies, useEffect will not be called again.

4

u/csorfab Oct 13 '20

I didn't notice your comment, but wrote the same thing below. I completely get that you're angry, I'm fed up with bullshit articles like this where the author doesn't even make the effort to actually check their fucking code if it indeed produces the results they write about. There are no excuses, this is pure laziness (and incompetence, at least with regards to JS/hooks). Anyone well versed with javascript and hooks would notice that the premise is flawed in 30 seconds. And juniors are learning their craft from shit articles like this... /r/javascript and /r/reactjs are being constantly spammed with a shitstorm of these... Well I guess the upside is, more jobs to me.

2

u/Rawrplus Oct 13 '20

Yeah I personally am not surprised by these articles being posted. But what really does amaze me is how these kind of articles get upvoted.

I think anyone who's at least late junior to mid-level should be able to identify this as an antipattern. So there's either some vote rigging going on or people just upvote random shit without even looking at it.

3

u/csorfab Oct 13 '20

Nah, it's really just mostly very incompetent people frequenting these subs. If you look at some of the discussions and what sorts of comments get upvoted, it's pretty evident. Good programmers are kind of rare, especially in the js/front end world.

3

u/SystemicPlural Oct 13 '20

Getting some articles written is now seen as a way to get a job. So juniors write them. Experienced devs are largely too busy to have time and they will get paid more by doing extra coding rather than writing tutorials.

1

u/grumd Oct 13 '20

Sounds very true.

52

u/[deleted] Oct 13 '20

Or move the function you're depended on into your useEffect.

9

u/Attack_Bovines Oct 13 '20

Yup. This is how the React docs do it.

1

u/straightouttaireland Oct 13 '20

What if the function is used elsewhere too?

14

u/csorfab Oct 13 '20

This example is wrong on multiple counts.

First off all, the effect in the example would not re-run on every re-render, because its dependency is a string, not a function, and strings always strictly equal (===, which is how useEffect decides equality) to themselves if they're the same string. So, if the url does not change, the effect will, correctly, only run once. The function reference never gets passed as props or deps, so it's completely unnecessary to wrap it in useCallback.

In this case it would make a bit more sense to store the result of the function call in a useMemo(), so we can at least spare the cpu from executing the potentially expensive function call every rerender (obviously it's not expensive in this case, but let's pretend). Mind you, the effect will run only once anyways because of the reasons above.

So an example that would at least make a little sense in this case would be the following:

function SomeComponent(props){
    function getUrl(id){
        return "https://some-api-url.com/api/" + id + "/"
    }
    const url = useMemo(() => getUrl(1), []);
    //do some other stuff here that might cause re-renders, like setting state
    return <DataFetcher url={url}>
}

6

u/Aswole Oct 13 '20

In addition to the mistake that other comments have pointed out (that the url prop is a static string here and thus it makes no difference whether the getUrl function is memoized or defined outside of the component), there is another mistake with this article that reveals a pretty serious misunderstanding of how React works:

Since by default all of SomeComponent’s code re-runs on render, getUrl gets re-defined every render. Meaning that because DataFetcher’s url prop changes every render, DataFetcher will also re-render every time SomeComponent re-renders.

No, no, no, no. DataFetcher will re-render every time SomeComponent re-renders because DataFetcher is a child of SomeComponent and because DataFetcher itself is not memoized. It has nothing to do with whether the url prop changes. Take the following code:

import * as React from "react";

const Child = () => {
  console.log('hello');
  return (
    <div>
      Check console logs
    </div>
  )
}

const MemoizedChild = React.memo(Child);

export default function App() {
  const [state, setState] = React.useState(0);
  return (
    <>
      <Child />
      <MemoizedChild />
      <button onClick={() => setState(prev => prev + 1)}>
        Update me
      </button>
    </>
  );
}

If you click on the button, which updates the App component's state, the Child component will be re-run, even though you aren't passing any props to it. MemoizedChild, on the other hand, will only be run once when it initially mounts. You can confirm this in your own testing by commenting out one or the other and reading the console logs for 'hello'.

So while prop equality comes into play in terms of it being used as the dependency in useEffects/useCallbacks/useMemos/etc, it is critical to understand that your components are still being re-rendered by default when a component higher up in the component tree updates. This isn't a huge deal if your components are pure as the output should be the same, and thus there isn't anything for React to do with the virtual dom (in respect to that component), but as applications grow in complexity, React.Context is introduced (either through Redux, custom hooks, etc), mistakes are made and impurities introduced to components, it is not a safe assumption that just because the props don't change that a component doesn't 're-render.'

15

u/jimbo_bones Oct 13 '20

Struggled with this for so long (particularly because of a eslint rule calling for all useEffect dependencies to be included). useCallback always feels kinda clunky but I guess it’s the way to go

13

u/Eux86 Oct 13 '20

Eslint rules are there for a reason. Usually a valid one (apart from the one that forces you to have properties of an object in alphabetical order -.-)

In general, if you don't get why eslint is complaining don't just shut it up, google it :D

12

u/jimbo_bones Oct 13 '20

There are plenty which are up for debate regarding their usefulness (I’m not claiming this is one of them). Agree that disabling rules just because they inconvenience you is a terrible idea though, tempting as it is sometimes

3

u/Eux86 Oct 13 '20

So tempting ahahah

6

u/severeXD Oct 13 '20

That reminds me I should have a stern talk with my linter.

4

u/csorfab Oct 13 '20 edited Oct 13 '20

Two simple rules:

Always use useCallback when creating a function you intend to pass as props or deps (or as argument to a custom hook).

Always use useMemo when you create an array or object you intend to pass as props or deps (or as arguments to a custom hook).

Edit: thinking more about it, it's not always feasible to wrap all of your array/object literals in useMemo, but the takeaway is that you need to be conscious that when you write <LocationDisplayer location={{ lng, lat }} /> or <Todos todos={rawTodos.map(convertRawTodo)} /> or <Filter filters={["one", "two"]} /> or stuff like this, a new object reference will be created, and unnecessary re-renders/effect runs may occur.

2

u/[deleted] Oct 13 '20 edited Oct 13 '20

Can someone explain this to me? It seems like the child component will always rerender.

If I have the following code

function Child({ fun }) {
  useEffect(() => {
    console.log("fun changed");
  }, [fun]);

  console.log("child");

  return <div />;
}

function Parent() {
  const [value, setValue] = useState(0);
  const fun = () => {};

  return (
    <div>
      <button onClick={() => setValue(value + 1)}>{value}</button>
      <Child fun={fun} />
    </div>
  );
}

"child" and "fun changed" will be logged every time value changes. However, if I wrap fun in useCallback then "fun changed" is only logged on the first render and "child" is logged every time value changes. So it would seem like the Child component rerenders every time the Parent component rerenders regardless of whether fun changes.

4

u/grumd Oct 13 '20

Components will always rerender when parent components rerender.

You have fun in useEffect dependencies, that's why console.log("fun changed"); is not called every rerender if you use a useCallback (because fun doesn't change).

If you want to also prevent Child from rerendering when fun doesn't change, wrap Child with React.memo()

1

u/[deleted] Oct 13 '20

What would the point be of wrapping fun in useCallback if the Child component is going to rerender every time Parent rerenders?

fun is only going to change when Parent is rerendered and Child is going to rerender whenever Parent rerenders, so I don't see the need for wrapping fun in useCallback.

If you were to wrap Child in useMemo, and you were to have fun as a dependency, then I could see why you would wrap fun in a useCallback.

2

u/grumd Oct 13 '20

You'd wrap it in useCallback to avoid running useEffect when it's not needed. But I'm not saying I would write a piece of code like that.

1

u/TheMcGarr Oct 13 '20

I'm so glad I read the comments!

1

u/pticjagripa Oct 13 '20

For those that read this article and see all the comments about how incorrect this is. Altought it is true that this is wrong use of useCallback the idea behind the article is pointing right direction, it's just execution that is flawed.

I hope that the author educate himself more and correct the mistakes so that not too many people will learn wrong.

1

u/rsandstrom Oct 14 '20

Bad article is bad. Poor writing on a subject it appears the author doesn’t fully understand themself and is now backtracking because the community is keeping them honest.

This is exactly the kind of writing that makes people more confused about certain features and in this case specifically the useEffect hook.

-17

u/X678X Oct 13 '20

could also just use a class component if you really want to hack your way around emulating lifecycle events 8)

6

u/grumd Oct 13 '20

Wrong answer. Components are bulky and unnecessary, and nobody was trying to emulate lifecycle events here. He's not trying to make a "componentDidMount", he was trying to make "fetch a url when url changes".