Refactor Inlined React setState Function to a setState Updater Factory

Share this video with your friends

Send Tweet

React's setState accepts an updater function that given current state returns new state. To better define and manage our setState usages, we can extract our inlined setState function to a setState updater factory. This enables us to give it a descriptive name, define required arguments, and ease future reuse, refactoring and composition for updating component state in our application.

bcyn
bcyn
~ 6 years ago

Why did you have to negate isLiked/newLiked? Seems to me it's just more confusing and doesn't functionally change anything, maybe I missed something.

Erik Aybar
Erik Aybar(instructor)
~ 6 years ago

Why did you have to negate isLiked/newLiked? Seems to me it's just more confusing and doesn't functionally change anything, maybe I missed something.

bcyn, the reason for negating newLiked was that by extracting into setTweetLiked(tweetId, newLiked) we moved away from "looking up a tweet's currently liked status (isLiked) within the setState function and toggling it" to now "invoking setTweetLiked with the desired liked status (newLiked) as a setter". isLiked as it was previously would be the opposite of newLiked.

So rather than saying "toggle the tweet's liked status", we can explicitly say "like the tweet" or "unlike the tweet". I preferred the setter to reduce ambiguity for setting/reverting state asynchronously that we might run into if we left this as a toggle based on current state at the time of setState invocation.

In retrospect it would have been more clear to rearrange the ternary such as shouldLike ? whenShouldLike : whenNotShouldLike rather than negating the condition as I did as !shouldLike ? whenNotShouldLike : whenShouldLike

I hope that helps clear things up. Good question really 😃