UseEffect in React

Daniel Andrew
2 min readNov 8, 2021

An incredibly useful tool in React is useEffect. This allows you to watch for changes in the state, and act on them however you like!

To use useEffect the basic structure is:

useEffect(() => {}, [])

Inside the function is whatever if going to happen each time the looked for state change occurs and inside the array is the state change that you are looking for.

In the above examples useEffect keeps an eye for the initialLoad state, as soon as it is first set (as false on the page load) the useEffect will trigger, within it it then does a secondary check to see if initialLoad is false, if so set to true.

This is where a loop could come in, as when the state changes the initialLoad useEffect will fire again. e.g

useEffect(() => {setState(!state)}, [state])

The above would trap you in an infinite loop of state flipping, as whenever the state changes from falsey to truthful and visa versa it will get changed back, therefore triggering the useEffect again, the addition of a simple if statement avoids all this kerfuffle.

useEffect(() => {
if(!state){
setState(!state)
}
}, [state])

Leaving the array of the useEffect empty looks for any change to state that occur, or you can can place multiple arguments in for it to look for the change in multiple different states. e.g

useEffect(() => {

}
}, [])
useEffect(() => {

}
}, [state1, state 2])

All in all its a very powerful way to keep an eye out for state in any component you are working in, and lets you chain together functions in an orderly and logical manner. It’s also dang handy for logging and bug fixing, as it can be very revealing as to what is currently happening in app.

Hope this was helpful :)

Keep calm and code on

Dan

--

--

Daniel Andrew

Old enough to have enjoyed Sid Miers Pirates on Windows 3.1 and deciding to delve out into more interesting waters.