DEV Community

Amrit Shenava
Amrit Shenava

Posted on

useEffect() makes life easier

import {useEffect} from 'react';

While building web applications in React, we often come across tasks where we want some activity or data to be displayed when the page loads automatically. For example, I have been building web applications for a while now where it greets the user with their name and puts some important data on the page after sign in successfully. In order to this, useEffect() helps a lot. useEffect() is called when a page loads and executes code within that code block.

Top comments (5)

Collapse
 
lexlohr profile image
Alex Lohr

I'm not going to disagree with the premise, but why was life hard to begin with? Could it be the design decision to re-run components required a lot of workarounds? useEffect's subscribe/unsubscribe pattern is merely being one of them; not the last one though, as useEvent is currently being discussed.

If you're interested to see how a framework without those workarounds looks like, try solid.js.

Collapse
 
amritshenava98 profile image
Amrit Shenava

Many beginners forget about useEffect. When I started out with React, I used to write lengthy functions and never knew about useEffect. Should have been more clear. This is my first post here on the platform.

Collapse
 
lexlohr profile image
Alex Lohr

Many beginners? How many? When it's literally the second thing you're shown about hooks? I find that slightly unbelievable, but never mind.

So you basically managed side effects directly in your component and filtered dependency changes and handled unsubscribes manually? Did you use a ref to do that?

Collapse
 
chadams profile image
Chad Adams

This is a bit inaccurate. useEffect is will be run an every render not on page load. What you really want is to load onMount? (sorta),

useEffect(()=>{ .. run on mount ...}, []) // <-- empty array
Enter fullscreen mode Exit fullscreen mode

or by passing an array of dependencies to useEffect

useEffect(()=>{ .. run on mount ...}, [...dependencies])
Enter fullscreen mode Exit fullscreen mode

of course this runs after the component is rendered (so its not really "onLoad") but for most cases this is what you want.

Now, because the function re-renders when dependencies change, this could also cause un-expected behavior, especially if a dependency is an object reference. This might require some calculated dependencies to be memoized with useMemo.

I've seen lots of code with many useEffect/useMemo/useCallback all over the place, definitely making the component complex.

I wouldn't say this "makes life easier", but, it does allow you to make react components without using classes (which is a plus imo)

Collapse
 
amritshenava98 profile image
Amrit Shenava

Apologies for the error. Will make updates to the post. Thank you for the feedback.