Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

App.js

import React from "react";
import CounterOne from "./CounterOne";
function App() {
  const [display, setDisplay] = React.useState(true);
  return (
    <>
      {display && <CounterOne />}
      <button
        onClick={() => {
          setDisplay(!display);
        }}
      >
        display
      </button>
    </>
  );
}

export default App;

CounterOne.js

import React, { useState } from "react";

function CounterOne() {
  const [count, setCount] = useState(0);
  React.useEffect(() => {
    console.log("component did update");
    return () => {
      console.log("component will unmount");
    };
  }, [count]);

  return (
    <div>
      <p>Count is {count}</p>
      <button
        onClick={() => {
          setCount(0);
        }}
      >
        reset
      </button>
      <button
        onClick={() => {
          setCount(count + 5);
        }}
      >
        Add 5
      </button>
      <button
        onClick={() => {
          setCount(count - 1);
        }}
      >
        Sub 1
      </button>
    </div>
  );
}

export default CounterOne;

When i hit the Add 5 or sub 1 button, the component re-render then in browser console it prints

component will unmount

component did update

i am confuse why will unmount part execute when the update of state taking place

question from:https://stackoverflow.com/questions/65941849/want-to-know-why-compoentwillunmount-execute-when-a-component-update

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
175 views
Welcome To Ask or Share your Answers For Others

1 Answer

Because when you change a state in a component, React will re-render the whole component. So the old component will be unmounted first, triggering the return callback in useEffect. When a new component is mounted, the logic inside useEffect will be triggered again, hence you see the "component did update" after the "component will unmount" message. More on useEffect here What is the expected return of `useEffect` used for?.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...