In this article, I will show you how to use React to replace useEffect in most cases.
I've been watching "Goodbye, useEffect" by David Khoursid, and it's 🤯 blows my mind in a 😀 good way. I agree that useEffect has been used so much that it makes our code dirty and hard to maintain. I've been using useEffect for a long time, and I'm guilty of misusing it. I'm sure React has features that will make my code cleaner and easier to maintain.
What is useEffect?
useEffect is a hook that allows us to perform side effects in function components. It combines componentDidMount, componentDidUpdate, and componentWillUnmount in a single API. It's a compelling hook that will enable us to do many things. But it's also a very dangerous hook that can cause a lot of bugs.
Why useEffect is dangerous?
Let's take a look at the following example:
import React, { useEffect } from 'react'
const Counter = () => {
const [count, setCount] = useState(0)
useEffect(() => {
const interval = setInterval(() => {
setCount((c) => c + 1)
}, 1000)
return () => clearInterval(interval)
}, [])
return <div>{count}</div>
}
It's a simple counter that increases every second. It uses useEffect to set an interval. It also uses useEffect to clear the interval when the component unmounts. The code snippet above is a widespread use case for useEffect. It's a straightforward example, but it's also a terrible example.
The problem with this example is that the interval is set every time the component re-renders. If the component re-renders for any reason, the interval will be set again. The interval will be called twice per second. It's not a problem with this simple example, but it can be a big problem when the interval is more complex. It can also cause memory leaks.
How to fix it?
There are many ways to fix this problem. One way is to use useRef to store the interval.
import React, { useEffect, useRef } from 'react'
const Counter = () => {
const [count, setCount] = useState(0)
const intervalRef = useRef()
useEffect(() => {
intervalRef.current = setInterval(() => {
setCount((c) => c + 1)
}, 1000)
return () => clearInterval(intervalRef.current)
}, [])
return <div>{count}</div>
}
The above code is a lot better than the previous example. It doesn't set the interval every time the component re-renders. But it still needs improvement. It's still a bit complicated. And it still uses useEffect, which is a very dangerous hook.
useEffect is not for effects
As we know about useEffect, it combines componentDidMount, componentDidUpdate, and componentWillUnmount in a single API. Let's give some examples of it:
useEffect(() => {
// componentDidMount?
}, [])
useEffect(() => {
// componentDidUpdate?
}, [something, anotherThing])
useEffect(() => {
return () => {
// componentWillUnmount?
}
}, [])
It's effortless to understand. useEffect is used to perform side effects when the component mounts, updates, and unmounts. But it's not only used to perform side effects. It's also used to perform side effects when the component re-renders. It's not a good idea to perform side effects when the component re-renders. It can cause a lot of bugs. It's better to use other hooks to perform side effects when the component re-renders.
useEffect is not a lifecycle hook.
import React, { useState, useEffect } from 'react'
const Example = () => {
const [value, setValue] = useState('')
const [count, setCount] = useState(-1)
useEffect(() => {
setCount(count + 1)
})
const onChange = ({ target }) => setValue(target.value)
return (
<div>
<input type="text" value={value} onChange={onChange} />
<div>Number of changes: {count}</div>
</div>
)
}
useEffect is not a state setter
import React, { useState, useEffect } from 'react'
const Example = () => {
const [count, setCount] = useState(0)
// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
// Update the document title using the browser API
document.title = `You clicked ${count} times`
}) // <-- this is the problem, 😱 it's missing the dependency array
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
)
}
I recommend reading this documentation: https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects
Imperative vs Declarative
Imperative: When something happens, execute this effect.
Declarative: When something happens, it will cause the state to change and depending (dependency array) on which parts of the state changed, this effect should be executed, but only if some condition is true. And React may execute it again for no reason concurrent rendering.
Concept vs Implementation
Concept:
useEffect(() => {
doSomething()
return () => cleanup()
}, [whenThisChanges])
Implementation:
useEffect(() => {
if (foo && bar && (baz || quo)) {
doSomething()
} else {
doSomethingElse()
}
// oops, I forgot the cleanup
}, [foo, bar, baz, quo])
Real-world implementation:
useEffect(() => {
if (isOpen && component && containerElRef.current) {
if (React.isValidElement(component)) {
ionContext.addOverlay(overlayId, component, containerElRef.current!);
} else {
const element = createElement(component as React.ComponentClass, componentProps);
ionContext.addOverlay(overlayId, element, containerElRef.current!);
}
}
}, [component, containerElRef.current, isOpen, componentProps]);
useEffect(() => {
if (removingValue && !hasValue && cssDisplayFlex) {
setCssDisplayFlex(false)
}
setRemovingValue(false)
}, [removingValue, hasValue, cssDisplayFlex])
It's scary to write this code. Furthermore, it will be normal in our codebase and messed up. 😱🤮
Where do effects go?
React 18 runs effects twice on the mount (in strict mode). Mount/effect (╯°□°)╯︵ ┻━┻ -> Unmount (simulated)/cleanup ┬─┬ /( º _ º /) -> Remount/effect (╯°□°)╯︵ ┻━┻
Should it be placed outside of the component? The default useEffect? Uh... awkward. Hmm... 🤔 We couldn't put it in render since it should be no side-effects there because render is just like the right-hand of a math equation. It should be only the result of the calculation.
What is useEffect for?
Synchronization
useEffect(() => {
const sub = createThing(input).subscribe((value) => {
// do something with value
})
return sub.unsubscribe
}, [input])
useEffect(() => {
const handler = (event) => {
setPointer({ x: event.clientX, y: event.clientY })
}
elRef.current.addEventListener('pointermove', handler)
return () => {
elRef.current.removeEventListener('pointermove', handler)
}
}, [])
Action effects vs Activity effects
Fire-and-forget Synchronized
(Action effects) (Activity effects)
0 ---------------------- ----------------- - - -
o o | A | o o | A | A
o o | | | o o | | | |
o o | | | o o | | | |
o o | | | o o | | | |
o o | | | o o | | | |
o o | | | o o | | | |
o o V | V o o V | V |
o-------------------------------------------------------------------------------->
Unmount Remount
Where do action effects go?
Event handlers. Sorta.
<form
onSubmit={(event) => {
// 💥 side-effect!
submitData(event)
}}
>
{/* ... */}
</form>
There is excellent information in Beta React.js. I recommend reading it. Especially the "Can event handlers have side effects?" part.
Absolutely! Event handlers are the best place for side effects.
Another great resource I want to mention is Where you can cause side effects
In React, side effects usually belong inside event handlers.
If you've exhausted all other options and can't find the right event handler for your side effect, you can still attach it to your returned JSX with a useEffect call in your component. This tells React to execute it later, after rendering, when side effects are allowed. However, this approach should be your last resort.
"Effects happen outside of rendering" - David Khoursid.
(state) => UI
(state, event) => nextState // 🤔 Effects?
UI is a function of the state. As all the current states are rendered, it will produce the current UI. Likewise, when an event happens, it will create a new state. And when the state changes, it will build a new UI. This paradigm is the core of React.
When do effects happen?
Middleware? 🕵️ Callbacks? 🤙 Sagas? 🧙♂️ Reactions? 🧪 Sinks? 🚰 Monads(?) 🧙♂️ Whenever? 🤷♂️
State transitions. Always.
(state, event) => nextState
|
V
(state, event) => (nextState, effect) // Here
Where do action effects go? Event handlers. State transitions.
Which happen to be executed at the same time as event handlers.
We Might Not Need an Effects
We could use useEffect because we don't know that there is already a built-in API from React that can solve this problem.
Here is an excellent resource to read about this topic: You Might Not Need an Effect
We don't need useEffect for transforming data.
useEffect ➡️ useMemo (even though we don't need useMemo in most cases)
const Cart = () => {
const [items, setItems] = useState([])
const [total, setTotal] = useState(0)
useEffect(() => {
setTotal(items.reduce((total, item) => total + item.price, 0))
}, [items])
// ...
}
Read and think about it again carefully 🧐.
const Cart = () => {
const [items, setItems] = useState([])
const total = useMemo(() => {
return items.reduce((total, item) => total + item.price, 0)
}, [items])
// ...
}
Instead of using useEffect
to calculate the total, we can use useMemo
to memoize the total. Even if the variable is not an expensive calculation, we don't need to use useMemo
to memoize it because we're basically trading performance for memory.
Whenever we see setState
in useEffect
, it's a warning sign that we can simplify it.
Effects with external stores? useSyncExternalStore
useEffect ➡️ useSyncExternalStore
❌ Wrong way:
const Store = () => {
const [isConnected, setIsConnected] = useState(true)
useEffect(() => {
const sub = storeApi.subscribe(({ status }) => {
setIsConnected(status === 'connected')
})
return () => {
sub.unsubscribe()
}
}, [])
// ...
}
✅ Best way:
const Store = () => {
const isConnected = useSyncExternalStore(
// 👇 subscribe
storeApi.subscribe,
// 👇 get snapshot
() => storeApi.getStatus() === 'connected',
// 👇 get server snapshot
true
)
// ...
}
We don't need useEffect for communicating with parents.
useEffect ➡️ eventHandler
❌ Wrong way:
const ChildProduct = ({ onOpen, onClose }) => {
const [isOpen, setIsOpen] = useState(false)
useEffect(() => {
if (isOpen) {
onOpen()
} else {
onClose()
}
}, [isOpen])
return (
<div>
<button
onClick={() => {
setIsOpen(!isOpen)
}}
>
Toggle quick view
</button>
</div>
)
}
📈 Better way:
const ChildProduct = ({ onOpen, onClose }) => {
const [isOpen, setIsOpen] = useState(false)
const handleToggle = () => {
const nextIsOpen = !isOpen;
setIsOpen(nextIsOpen)
if (nextIsOpen) {
onOpen()
} else {
onClose()
}
}
return (
<div>
<button
onClick={}
>
Toggle quick view
</button>
</div>
)
}
✅ Best way is to create a custom hook:
const useToggle({ onOpen, onClose }) => {
const [isOpen, setIsOpen] = useState(false)
const handleToggle = () => {
const nextIsOpen = !isOpen
setIsOpen(nextIsOpen)
if (nextIsOpen) {
onOpen()
} else {
onClose()
}
}
return [isOpen, handleToggle]
}
const ChildProduct = ({ onOpen, onClose }) => {
const [isOpen, handleToggle] = useToggle({ onOpen, onClose })
return (
<div>
<button
onClick={handleToggle}
>
Toggle quick view
</button>
</div>
)
}
We don't need useEft for initializing global singletons.
useEffect ➡️ justCallIt
❌ Wrong way:
const Store = () => {
useEffect(() => {
storeApi.authenticate() // 👈 This will run twice!
}, [])
// ...
}
🔨 Let's fix it:
const Store = () => {
const didAuthenticateRef = useRef()
useEffect(() => {
if (didAuthenticateRef.current) return
storeApi.authenticate()
didAuthenticateRef.current = true
}, [])
// ...
}
➿ Another way:
let didAuthenticate = false
const Store = () => {
useEffect(() => {
if (didAuthenticate) return
storeApi.authenticate()
didAuthenticate = true
}, [])
// ...
}
🤔 How if:
storeApi.authenticate()
const Store = () => {
// ...
}
🍷 SSR, huh?
if (typeof window !== 'undefined') {
storeApi.authenticate()
}
const Store = () => {
// ...
}
🧪 Testing?
const renderApp = () => {
if (typeof window !== 'undefined') {
storeApi.authenticate()
}
appRoot.render(<Store />)
}
We don't necessarily need to place everything inside a component.
We don't need useEffect for fetching data.
useEffect ➡️ renderAsYouFetch (SSR) or useSWR (CSR)
❌ Wrong way:
const Store = () => {
const [items, setItems] = useState([])
useEffect(() => {
let isCanceled = false
getItems().then((data) => {
if (isCanceled) return
setItems(data)
})
return () => {
isCanceled = true
}
})
// ...
}
💽 Remix way:
import { useLoaderData } from '@renix-run/react'
import { json } from '@remix-run/node'
import { getItems } from './storeApi'
export const loader = async () => {
const items = await getItems()
return json(items)
}
const Store = () => {
const items = useLoaderData()
// ...
}
export default Store
⏭️🧹 Next.js (appDir) with async/await in Server Component way:
// app/page.tsx
async function getData() {
const res = await fetch('https://api.example.com/...')
// The return value is *not* serialized
// You can return Date, Map, Set, etc.
// Recommendation: handle errors
if (!res.ok) {
// This will activate the closest `error.js` Error Boundary
throw new Error('Failed to fetch data')
}
return res.json()
}
export default async function Page() {
const data = await getData()
return <main></main>
}
⏭️💁 Next.js (appDir) with useSWR in Client Component way:
// app/page.tsx
import useSWR from 'swr'
export default function Page() {
const { data, error } = useSWR('/api/data', fetcher)
if (error) return <div>failed to load</div>
if (!data) return <div>loading...</div>
return <div>hello {data}!</div>
}
⏭️🧹 Next.js (pagesDir) in SSR way:
// pages/index.tsx
import { GetServerSideProps } from 'next'
export const getServerSideProps: GetServerSideProps = async () => {
const res = await fetch('https://api.example.com/...')
const data = await res.json()
return {
props: {
data,
},
}
}
export default function Page({ data }) {
return <div>hello {data}!</div>
}
⏭️💁 Next.js (pagesDir) in CSR way:
// pages/index.tsx
import useSWR from 'swr'
export default function Page() {
const { data, error } = useSWR('/api/data', fetcher)
if (error) return <div>failed to load</div>
if (!data) return <div>loading...</div>
return <div>hello {data}!</div>
}
🍃 React Query (SSR way:
import { getItems } from './storeApi'
import { useQuery } from 'react-query'
const Store = () => {
const queryClient = useQueryClient()
return (
<button
onClick={() => {
queryClient.prefetchQuery('items', getItems)
}}
>
See items
</button>
)
}
const Items = () => {
const { data, isLoading, isError } = useQuery('items', getItems)
// ...
}
⁉️ Really ⁉️ What should we use? useEffect? useQuery? useSWR?
or... just use() 🤔
use() is a new React function that accepts a promise conceptually similar to await. use() handles the promise returned by a function in a way that is compatible with components, hooks, and Suspense. Learn more about use() in the React RFC.
function Note({ id }) {
// This fetches a note asynchronously, but to the component author, it looks
// like a synchronous operation.
const note = use(fetchNote(id))
return (
<div>
<h1>{note.title}</h1>
<section>{note.body}</section>
</div>
)
}
Fetching in useEffect problems
🏃♂️ Race conditions
🔙 No instant back button
🔍 No SSR or initial HTML content
🌊 Chasing waterfall
- Reddit, Dan Abramov
Conclusion
From fetching data to fighting with imperative APIs, side effects are one of the most significant sources of frustration in web app development. And let's be honest, putting everything in useEffect hooks only helps a little. Thankfully, there is a science (well, math) to side effects, formalized in state machines and statecharts, that can help us visually model and understand how to orchestrate effects, no matter how complex they get declaratively.
Latest comments (51)
PLEASE READ DOCUMENTATION OF TECHNOLOGIES YOU USE BEFORE YOU START COMPLAINING ABOUT IT...
please delete this post. you are misleading other people especially juniors!
The first example and description do not seem to match. Either remove the dependency array of the first example or clearly state that it could be easily forgotten and thus create problems.
At the second example you say "The above code is a lot better than the previous example", it however is not. It is a worse actually.
Maybe I misunderstand, but when
useEffect
has a dependency array that is empty it will not trigger on each render.You're correct, I was typo when copy-pasting from the source code. It suppousedly not written like that.
Still the point is, don't use useEffect for everyhting.
You're misleading people with your opening example. The effect does not run on every render when you use an empty dependency array. Effects only run when a dependency changes, an empty array means they don't run until the component is mounted again (not rendered again). What would the point be of specifying the depdendency array if the effect ran on every render?
So I feel kinda bad that you wrote a lot more to this article when you couldn't get the basics right. I didn't read it because it wouldn't be worthwhile reading the ideas of someone who doesn't understand the concepts, but can you please just delete this or something so you don't mislead a lot of people?
I'm sorry for that example, It was my fault copying it from false clipboard history. I think I should fix it before any junior mislead by this example.
Thank you for pointing out.
You say it's a mistake with copy and pasting but your next code sample follows on from it.
Then your next code sample also does things with
useRef
that do nothing but make the code more complicated, more verbose and less performant.Could you please delete this post before other developers who might not have so much knowledge of understanding get misled by it. Having incorrect information about programming online has the potential to be really harmful to others and yourself.
Ikr
As a newbie, it's kinda hard to distinguish between valid info and the opposite especially when the OP has a lot of followers.
@harmonygrams this article is trash. dont read it
The best way is to move all the business logic out from the components and the React code. A good candidate to use is — effector. It can handle all business logic cases without ruining logic with View-framework implementation details
yep, don't just mix everything in a single place if there is no purpose behind it. It'll be better if we split and move every part of our code with purpose and objective.
Clearly, author has no good understanding of
useEffect
and yet has written a massive article about its dangers.The empty dependency array will make effect run only once when component mounts. It is in the docs.
The second example that claims to fix the issue does not actually do anything useful at all. There is absolutely no need to store the interval in the reference as it is perfectly fine inside the closure in the example #1.
This is so exemplary of what the modern internet knowledge have become: anyone posts whatever they believe and a fair bunch of others will consume it as expert knowledge (look at 71 likes!) multiplying amounts of nonsense which is already plentiful in the internet.
I know, and in spite of all the comments pointing out what a harmful and mistaken article it is, they won't delete it.
This is the new hot take era of "software development". YouTube promising "learn React in 5 hours", social media, and sites like dev.to here, contribute to people thinking they should be teaching others when they don't really have an understanding of the tools they're using. I love that more people are interested in programming, but too many don't grasp where they are in their journey and then repeat the same bad advice they read.
Meanwhile in Svelte
<script>
let c = 0;
setTimeout (() => c++, 1000);
</script>
<div>{c}</div>
🤣 good comparison
thanks, now I think to my self, why is useEffect sold as a replacement to the react lifecycles if it is causing so much trouble and confusion?.
Because it is the only solution right now, and XState gave us another solution also.
We should pay a lot attention to prevent useEffect from causing a bug or make the code messy.
Consider doing some positive things (e.g. contributing to main post, open a discussion, etc.) or please be quite.
Your comment not helping nor useful to anyone who didn't understand ur point of view.
It's not a point of view, it's objective reality. The existence of this article is only going to confuse and mislead people, especially juniours, pointing that out is helpful.
So what are the differences between React and useEffect? . From what I know useEffect is one of the feature from React.
Is there a new framework called useEffect?
saying sorry for laughing but you put a laughing emoji is the same as you laughing at me 👎
don't mock someone if they don't know at something. In the title you compare
React
library withuseEffect
feature inReact
. The title is confusing.I'm starting to like React better as I'm getting the hang of it - but then again, when seeing an article like this with "useEffect is not for effects", followed by a ton of different ways we "should" do things instead, yeah well it just gives me the creeps ...
How come we never have these kinds of discussions when it's about other frameworks like Vue and so on? The answer is, because frameworks like Vue and the like are more batteries included, and built on more sound principles - a lot of what I see in React feels like a kludge.
If that is the argument for React, you should be doing COBOL; pays more than React nowadays
LOL you could be right - so where are the COBOL articles here on dev.to?
COBOL devs stopped using Internet technologies after Gopher; WWW was just a fad.
To be serious; what if React is the new COBOL?
Right - yes, COBOL devs just stick to their tried-and-true 3 meters of printed IBM manuals ... :)
React the new COBOL? I think Java is already the new COBOL, maybe React can then become the new Java?
useEffect is a really useful tool and solves a lot of common problems in react... Yeah there are plenty of antipatterns that newbies often create when using it, but that's not the tools fault.
The idea that useEffect is bad in anyway is misguided, it makes certain things that were really annoying to do in the past easy.
Side note - If your state is so complex in React that you need a state chart to understand it, then you're probably doing something wrong. Application state doesn't need to be complex for most apps. Keeping your state simple should always be the first step
Some comments have been hidden by the post's author - find out more