0

In a React app I get this warning on a few components in the useEffect function. I have seen other SO questions but still cant see a fix.

React Hook useEffect has a missing dependency: 'digiti' and 'time'. Either include it or remove the dependency array

const GenerateNumber = (props) => {
    const [number, setNumber] = useState(0);
    // add side effect to component
    useEffect(() => {
        const interval = setInterval(
            () => setNumber(Math.floor(Math.random() * 9 + 1)),
            50
        );

        setTimeout(() => { clearInterval(interval); setNumber(props.digiti); }, props.times * 100);

    }, []);

    return (
        <span className='digit'>{number}</span>
    );
}
1
  • did you try this [props.digiti, props.times];? Commented Mar 28, 2022 at 8:15

1 Answer 1

2

This is something the react hooks exhaustive deps explain. In general, your dependency array should include all values used in the dependency array, however when you do this with something like setNumber, your useEffect hook will run infinitely as each change of setNumber triggers a new render (and each new render triggers setNumber, see the problem there?).

Your actual error, with the prop values of both digiti and times aim at you adding these two values to the dependency array, which would case the useEffect hook to run again every time these props change. It is up to you if this is intended behavior.

What is actually documented in the dependency array documentation is that it is intended behavior to leave the array empty to have the useEffect hook run exactly once.

Sign up to request clarification or add additional context in comments.

2 Comments

Hendiks I plan to create an animation that runs like: codepen.io/Ahmed_B_Hameed/pen/LZqNmp?editors=0010 . Can you give me another suggestion?
Well as I mentioned, an empty dependency array is actually intended behavior. You can simply leave it empty and ignore the warning (or use your IDE's help to suppress the warning)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.