0

I'm studying React hooks and I noticed a strange behavior, can someone explain to me why?

The component is mounted, sets the state to the initial value and then is unmounted, to be mounted and updated again!!!

I understand that every update the component is re-rendered, but why is the componentWillUnmounted method (in this case useEffect's return) called?

I had the same strange behavior when I was studying class component and life cycles...

root component

    function App() {
    const [visible, setVisible] = useState(true);

    return (
        <div className='App'>
            {visible && <UseEffect />}
            <button onClick={() => setVisible((visible) => !visible)}>
                Show/Hide
            </button>
        </div>
    );
}

child component

const UseEffect = (props) => {
    const [counter, setCounter] = useState(0);

    //didMounted
    useEffect(() => {
        console.log('Cp Mounted');

        //didUnmounted
        return () => {
            console.log('Cp UnMounted');
        };
    }, []);

    //didUpdate
    useEffect(() => {
        console.log('Cp Updated');
    });

    //with state
    useEffect(() => {
        console.log('Change 'counter');
    }, [counter]);

    return (
        <div>
            <h1>{counter}</h1>
            <button onClick={() => setCounter(counter + 1)}>+</button>
        </div>
    );
};

output browser console

enter image description here

This is driving me crazy!!! Please someone know explain why this happen?

Thx

Ed Lucas
  • 5,955
  • 4
  • 30
  • 42
M.F
  • 45
  • 7

1 Answers1

1

Disable <StrictMode></StrictMode> in index.js file you won't get component unmounted and mounted again, the strict mode make sure there was not bugs while rendering components twice, and that's why you see the mounting behaviour

Check out sand box

Enfield Li
  • 1,952
  • 1
  • 8
  • 23
  • Thx! This work but, by disabling strict mode can cause any future issues? And can this initial double rendering cause problems too or is it just annoying? – M.F Jun 03 '22 at 13:00
  • Not that I'm aware of. It is only present in dev mode while disabled in production – Enfield Li Jun 03 '22 at 13:59