Home > database >  In React, why useState(foo()) call foo in every rerendering
In React, why useState(foo()) call foo in every rerendering

Time:12-25

In React I know next code call foo one time in mount

(...)
function foo() {
 return {
      id: 1,
      text: 'hello',
    }
}

const App = () => {
  const [value, setter] = useState(foo);
(...)

but if I change the foo(useState's argument) to foo() this code call foo if App is rerendering.

I know the difference Between foo and foo() but I know why the difference is occur

CodePudding user response:

The code first(second()) means to call second, and pass its result into first. So every time a line like this runs, second will be called. Swap in the names in your code and we get useState(foo()), and it behaves the same. Every time this line runs, foo will be called.

As for why the other version only calls it once, that's because the useState hook is designed so that it if it receives a function, it will call that function on the first render only. On subsequent renders, you will still pass the function in, but react sees that this isn't the first render and so it does not call your function.

CodePudding user response:

Function calls in a function body must be evaluated by the JS engine, it doesn't know that React is going to ignore the result on subsequent renders.

It's just like any other function call in the control flow. It has to be evaluated before JS can call useState.

If you send the function reference instead, the implementation of useState knows only to evaluate it on mount.

  • Related