I have been trying to understand when is unsubscribe(the callback in useEffect) gets called exactly.
This is the codepen link : https://codepen.io/deen_john/pen/eYmNdMy Code :
const { useState, useEffect } = React ;
function App() {
const [count, setCount] = useState(0);
// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
// Update the document title using the browser API
document.title = `You clicked ${count} times`;
console.log("use effect called ");
return () => {
console.log("unsubscribe ")
}
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
ReactDOM.render(<App />, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Problem : In my example, the callback function in useEffect hook (i.e unsubscribe) , gets called every time i click on button (i.e every time i update the button state). But, as per the React documentation, callback in useEffect works like componentWillUnmount lifecycle , so in my example it should have been called only if the App component is unmounted. I am just updating the button state here,not unmounting App component on every click.