Search code examples
reactjsreact-hooksuse-effect

React Hooks: useEffect with dependecy also called when component mounts


In React, you can use useEffect() hook with a dependency on it.

const [data, setData] = useState();

useEffect(() => {
    console.log(data.test.test);
}, [data]);

So I would assume that this useEffect is just called when the data is changed. So let´s assume I would make an api call and use setData(response.data).

Then the useEffect() should be triggerd, since the data state is a dependecy.

Then the console.log(data.tes.test) would be working, since I got the right data. However, I get an undefined error, which comes from the fact that useEffect() is also called initially.

How can I avoid this? This is pretty annoying and in my mind not a good design with regard to adding a dependency.


Solution

  • You have two solutions. As @Woohaik has already mentioned, checking for data existence in the useEffect. I'd implement a guard:

    useEffect(() => {
      if (!data) return
      console.log(data.test.test)
    }, [data])
    

    or you could make yourself acquainted with optional chaining (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining):

    useEffect(() => {
      console.log(data?.test?.test)
    }, [data])