1

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?

dcripplinger
  • 125
  • 1
  • 8
  • 1
    Yes, call them as many times as you need. perfectly fine. If you do decide to bundle your state and use an object don't `useState`, `useReducer` instead. same with `useCallback`, keep them separate so they only do one thing instead of bundling multiple stuff in the same callback – azium Feb 17 '20 at 23:49
  • 2
    "how does useState know whenever it's called whether it's referring to the already stored" --- it's where the order requirement comes from. They must all come in the same order every render – zerkms Feb 17 '20 at 23:49
  • Does this answer your question? [React Hooks - What's happening under the hood?](https://stackoverflow.com/questions/53729917/react-hooks-whats-happening-under-the-hood) – Emile Bergeron Feb 18 '20 at 00:09
  • Hooks are designed to be used multiple times, so yes, it's perfectly fine (and encouraged) to split state across multiple `useState` hooks, split function declarations across multiple `useCallback` hooks, and split side effects across multiple `useEffect` hooks. – JMadelaine Feb 18 '20 at 05:40

1 Answers1

4

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:

zerkms
  • 249,484
  • 69
  • 436
  • 539
  • Thanks! That was precisely the section of the documentation I was trying to find to answer my question and had a hard time coming across it. – dcripplinger Feb 18 '20 at 15:46