Issues with useEffect

Rajan Lagah
2 min readAug 4, 2022

If you are react dev you surely encounter multiple use cases for useEffect. But let me show how useEffect is tricking you all these times.

You want some function to run when component mounts


useEffect(() => …fn() )

But now you want function to run when some specific state value is changed


const [data, setData] = useState(“”);
useEffect(() => {
console.log(“Running useEffect”);
}, [data]);

our expectation is that this function will run when data is changed.

Check this small example.

Here we can see that useEffect callback ran even if I don’t change data.
That is because useEffect will run at least once on component mount.

So what is fix here?

We all use this to make some api calls and do some critical work and due to this behaviour of useEffect we can face bugs or performance issue.

So to run it only when data is changed we can.


import { useState, useEffect, useRef } from “react”;
export function App() {
const isMounted = useRef(false);
const [data, setData] = useState(“”);

useEffect(() => {
if (isMounted.current) {
console.log(“HERE”);
} else {
isMounted.current = true;
}
}, [data]);

return (
<div>
<input
onChange={(e) => setData(e.target.value)}
placeholder=”First name”
/>
</div>
);
}

Now in the console you will not see HERE on mount.

Notice here we are using useRef specifically so that on re-render value of isMounted persist else with simple js variable it will keep reseting on every mount.

Hit like if you have learned something awesome.

--

--