DEV Community

Cover image for Issues with useEffect
Rajan lagah
Rajan lagah

Posted on

Issues with useEffect

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() )
Enter fullscreen mode Exit fullscreen mode

Everything is good here.

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

 const [data, setData] = useState("");
 useEffect(() => {
    console.log("Running useEffect");
  }, [data]);
Enter fullscreen mode Exit fullscreen mode

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

Image description

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>
  );
}
Enter fullscreen mode Exit fullscreen mode

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

Image description

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.

Top comments (2)

Collapse
 
rajanlagah profile image
Rajan lagah

Nice.
But what exactly is wrong? 🧐
The example?

 
rajanlagah profile image
Rajan lagah

Got it. Thankyou for letting me know this. Will update