M.F
M.F

Reputation: 115

Why is my React component always mounted, unmounted and mounted again?

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

Upvotes: 5

Views: 4148

Answers (1)

Enfield Li
Enfield Li

Reputation: 2530

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

Upvotes: 6

Related Questions