How to avoid it?
If your effect depends on any value from the component scope, make sure to include it in the dependency array. If the effect should only run once, pass an empty dependency array and ensure the effect doesn’t rely on external variables.
Example:
Javascript
// App.js import React, { useEffect, useState } from 'react' ; const App = () => { const [count, setCount] = useState(0); const handleClick = () => { setCount(count + 1); }; useEffect(() => { console.log( 'Effect ran!' ); }, [count]); /* Dependency array is empty, runs only once 'count' is included in the dependency array */ return ( <div> <p>Count: {count}</p> <button onClick={handleClick}> Increament Value </button> </div> ); }; export default App; |
Output:
What are the pitfalls of using hooks, and how can you avoid them?
Using hooks in React comes with great benefits, but there are potential pitfalls that users need to be aware of. Common issues include stale closures and incorrect dependency arrays in the useEffect
hook.
Contact Us