Search code examples
reactjsreact-hooksusecallbackuse-state

Can you call React's useState and useCallback multiple times in a single functional component? If so, how does it work?


I couldn't find any mention of this yet in the official React docs or on the blagosphere.

I think you can and usually should do something like this when you have more than one state variable:

function MyComponent() {
  const [foo, setFoo] = useState(0);
  const [bar, setBar] = useState(1);

  return (
    <div>
      <div onClick={() => setFoo(foo+1)}>{foo}</div>
      <div onClick={() => setBar(bar+1)}>{bar}</div>
    </div>
  );
}

Is this allowed and encouraged, as opposed to calling useState a single time with an all-encompassing object called state which has fields foo and bar? If it is allowed and encouraged, how does useState know whenever it's called whether it's referring to the already stored foo or the already stored bar?

I also have basically the same question about useCallback. I've wondered, if I call useCallback twice in the same component to create two different callbacks, how does useCallback know that I meant to reference a function defined before vs create a new one, and if referencing an already used function it needs to return the memoized version of, how does it know which of the two? Especially if both callbacks have the same list of dependencies?


Solution

  • It's fine to use multiple useState in your render function.

    One important requirement is that their number and order should always be the same.

    References: