A tricky useEffect dependency

The following code returns 1. It is tricky but should be eye opener.

export default function App() {
    const [state, setState] = useState('');
    useEffect(()=>{
        console.log(1)
    },[setState])
    return (
        <div>
            <h1>Hello StackBlitz!</h1>
            <p>Start editing to see some magic happen :)</p>
        </div>
    );
}
which is same as
export default function App() {
    const [state, setState] = useState('');
    useEffect(()=>{
        console.log(1)
    },[])
    return (
        <div>
            <h1>Hello StackBlitz!</h1>
            <p>Start editing to see some magic happen :)</p>
        </div>
    );
}
The following will throw an error
Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.
export default function App() {
    const [state, setState] = useState('');
    setState(1);
    useEffect(()=>{
        console.log(1)
    },[])
    return (
        <div>
            <h1>Hello StackBlitz!</h1>
            <p>Start editing to see some magic happen :)</p>
        </div>
    );
}

We need to set state inside event handler function.

export default function App() {
    const [state, setState] = useState(0);
    const onClickHandler=()=>{
        setState(1);
    }
    useEffect(()=>{
        console.log(state)
    },[state])
    return (
        <div>
            <h1>Hello StackBlitz!</h1>
            <button onClick={onClickHandler}>click</button>
        </div>
    );

About the Author

Pravin Varma

Tech Lead at Calsoft

You may also like these