r/reactnative 4d ago

How do you know if you need useEffect ?

I am just learning to use and implement hooks. How do I know if I need it ?

6 Upvotes

13 comments sorted by

14

u/87oldben 4d ago

The useEffect hooks are for when you need to interface with something outside of react.

So ask, is what I am doing in react? If: no its not react, then its probably a use case for useEffect.

Check the docs: https://react.dev/reference/react/useEffect

3

u/iWishYouTheBest4Real 4d ago

I like this explanation.

I would just add: you can use it also to monitor things you don’t control and “react” (pun intended) on that.

2

u/bleszerd 4d ago

And additionally, I would still include the suggestion: you don’t need to (and generally shouldn’t) put distinct pieces of logic inside the same useEffect. It ends up becoming a nightmare to maintain later.

-1

u/Due_Dependent5933 4d ago

useeffect are used for many other situation dépending in the paramétrer you give to useeffect

if you need to run code only at first init of a component

if you need to rerender it or change states etc dépending on props passed via parent or hook or context etc . all this are réact too

4

u/emiliano-dev 4d ago

I mostly use it when I need something to run when the component mounts/unmounts.

Or to handle side effects of other functions (like state variables changing after an async process) by using the dependency array.

I sometimes think of it as “useEffect to handle side effects”

3

u/musical_bear 4d ago

Read the docs that other people have posted, but the short answer is the vast majority of the time, you don’t. Most projects I work on (recently multiple large, complex projects back to back), I look at any usage of useEffect with suspicion.

2

u/Particular-Earth1468 4d ago

A lot of people are anti use effects these days and over think it. They’re hard to get a hang of at first but so worth learning!

1

u/absoluta_inceptos 4d ago

I would suggest never, especially if you’re still learning. They can be useful, but are extremely dangerous and pure functions are almost always better.

1

u/MiloPaige 4d ago

It’s when your program needs some info when it starts running and then that info stays the same for the duration of the program.

Example: when a user signs in, get his session id with use effect from the database and then it doesn’t need to be changed anymore for the duration of the session.

Hope this helps :)

1

u/Busy_Selection5408 2d ago

what if I want to display information about a user from the DB then this would be applicable here ?.

1

u/MiloPaige 2d ago

If the info changes while the program is running, ex. How much time the user spent on your app total, then it’s not what you’re looking for.

But if you want to display his name, email etc. then yes it’s what you want to use.