Loading video...

Video Failed to Load

Go Home

❌ Avoid deriving state in useEffect in React, this can create multiple unnecessary render phases. ✅ Instead derive the state directly in the event handler, this way you'll have one single render phase. ↓

33,474 views • 1 year ago •via X (Twitter)

11 Comments

Nikhil S's profile picture
Nikhil S1 year ago

A more simple approach in this case is to derive the value during render const isValid = isYearOfBirthValid(yearOfBirth)

Christian Esmann's profile picture
Christian Esmann1 year ago

I just launched an all-in-one template for cross-platform development, based on the stack I use myself everyday. Expo, NextJS, TypeScript, Tailwind, Firebase, AppsFlyer, Authentication, Analytics, In-App Purchases, Stripe and a lot more, setup by default.

mikhaylovich's profile picture
mikhaylovich1 year ago

is it valid to replace all of that (useEffect + useState) with an useMemo? it still tracks each change on yearOfBirth, applies the validation, returns 'isValid' but also drops the extra useState on isValid and it's much cleaner (also setYearOfBirth is moved to onChange)

Fabrizio's profile picture
Fabrizio1 year ago

This is as much as an antipattern as the useEffect solution, just derive during the render and add useMemo if needed (only if needed)

Ryan Faust's profile picture
Ryan Faust1 year ago

As a self learned coder, I didn't know this. Or many other best practices. Your content is gold for me.

Toyyib 💙's profile picture
Toyyib 💙1 year ago

@Rhoy__b @ibr9heem

Ali Bey's profile picture
Ali Bey1 year ago

I avoid useEffect whenever I can

Travis Watson's profile picture
Travis Watson1 year ago

useMemo is gonna blow your mind

Mmina_SCRM Solutions's profile picture
Mmina_SCRM Solutions1 year ago

deriving state in event handlers is a smart move. it cuts down on extra renders, making your app run smoother. keep it efficient, especially in complex components.

shubham Gupta's profile picture
shubham Gupta1 year ago

This is a great insight. The animation in your post is super clean—may I ask which tool you used to create it?

tna 7792's profile picture
tna 77921 year ago

The official documentation explains this in detail.

Related Videos