Skipping the first call to a useEffect — what’s a good way to do that?

Rahul Shah
2 min readApr 22, 2021

--

I’ve faced this problem so many times. I have a useEffect, but I only want it triggered when state changes and not on the first render. Typically, I would initialize a state variable (say isFirstRender) as true and then change it to false the first time the component renders. But that always felt wrong. I mean, that state variable is going to be observed for the rest of the lifetime of the component - waiting for it to change — but it will never. How sad :(

Ahh! But wait — there’s a better way to do it! Instead of using state, we can use a ref. Just define a ref (say componentJustMounted) and initialize it with a true value. The first time the component renders, set componentJustMounted.current to false and it’s done.

No extra state, works consistently — it feels like a good solution. Let me know in the comments if you have any other too!

P.S. I wish I came up with this idea by myself, but credit to Ohans Emmanuel.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Rahul Shah
Rahul Shah

Written by Rahul Shah

React developer - Passionate riddle solver - Lifelong learner

No responses yet

Write a response