re: When should we use the appropriate way to set state? VIEW POST

re: ** update ** Woops, 😅 I didn't catch that #explainlikeim5 tag... Hi Brian, Those two examples are actually recommended ways. From what I read ...

Hi Sung,

Thanks for your reply!

Perhaps my question wasn't clear enough, sorry for that. I posted the two options (from the React docs) knowing that those were the correct ways to implement state, BUT my question is when to use one over the other. Why are there two correct ways when Option 2, IMO, should always be used. Why have Option 1, when there's Option 2? Hope that clears it up.


Yikes.. I am sorry I misunderstood the question 😰

How I understood was that they are basically the same providing devs multiple ways to do the same thing depending on your need.

So if you don't need to use previous state or props, then go with option 1 else option 2.

Unrelated to the main question,
For memoization in React Hooks, they have two different ways to memoize (useCallback & useMemo, which do the same thing but useCallback is called like Option 1 of setState, while useMemo is called like Option 2 of setState).

Official doc shows that

useCallback(fn, inputs) is equivalent to useMemo(() => fn, inputs).

But I don't know enough history about React why there is only setState but two for memoization 😅

code of conduct - report abuse