Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 142327

Why is a state variable's setter needed as a dependency with useEffect when passed in through props?

$
0
0

Compare the following two components:

Child.js

import React, { useEffect } from "react";

function Child({ count, setCount }) { // Note: Has parameter
  useEffect(() => {
    setInterval(() => {
      setCount(prevCount => prevCount + 1);
    }, 1000);
  }, []);

  return <div>{count}</div>;
}

export default Child;

Child2.js

import React, { useEffect, useState } from "react";

function Child2() { // Note: No parameter
  const [count, setCount] = useState(0); // State variable assigned in component

  useEffect(() => {
    setInterval(() => {
      setCount(prevCount => prevCount + 1);
    }, 1000);
  }, []);

  return <div>{count}</div>;
}

export default Child2;

They are essentially the same. The difference between the two is that Child.js gets the state variable count and its setter setCount passed in from its parent, while Child2.js sets that state variable itself.

They both work fine, but Child.js (and only Child.js) complains about "a missing dependency: 'setCount'." Adding setCount to the dependencies array makes the warning go away, but I'm trying to figure out why that's necessary. Why is the dependency required in Child but not Child2?

I have working examples at https://codesandbox.io/s/react-use-effect-dependencies-z8ukl.


Viewing all articles
Browse latest Browse all 142327

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>