I have a useEffect that should be running at first render and a second useEffect that should be running only when state count
changes, but both of them are running at first render. I use the useRef hook to track whether the component has mounted or not. It should start out as false and once the effect runs for the first time, it should change to true. The thing is that I get logged not first render
even in the first render. I give my code:
const { useEffect, useRef, useState } = React;
const Component = () => {
const [count, setCount] = useState();
const isMounted = useRef(false);
useEffect(() => {
console.log("first render");
}, []);
useEffect(() => {
if (isMounted.current) {
console.log("not first render");
} else {
isMounted.current = true;
}
}, [count]);
return (
<div>
<button
onClick={() => {
setCount(count + 1);
}}
>
Click Me
</button>
</div>
);
};
ReactDOM.createRoot(document.body).render(<Component />);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>
If anyone could explain me why it is happening I would be very grateful. Thanks.