useEffect hook

DEMO
Console
There are 3 main stages in a component's lifecycle:
1. 
Mount - Component is added to DOM
2.
Update - Component rerenders due to a change in props or state
3.
Unmount - Component is removed from DOM

See the console above to understand the behaviour of useEffect in these different stages.

The useEffect hook's callback will always run after the first render, and after every update (unless dependency array is empty).

UseEffectDemo.jsx

function UseEffectDemo() {
  const [name, setName] = React.useState("");
  const [address, setAddress] = React.useState("");

  React.useEffect(() => {
    // only happens once (commonly used to fetch data)
    console.log("component mounted");

    // optional clean-up function
    return () => {
      // e.g. when you go back to the home page
      console.log("component about to unmount");
    };
  }, []);

  React.useEffect(() => {
    console.log("component updated");
  });

  React.useEffect(() => {
    // runs every time the example1 state is updated
    console.log(`Your address: ${address}`);
  }, [address]);

  return (
    <form>
      <Label>
        Name
        <Input
          placeholder="Enter your name..."
          value={name}
          onChange={(e) => setName(e.target.value)}
        />
      </Label>
      <Label>
        Address
        <Input
          placeholder="Enter your address..."
          value={address}
          onChange={(e) => setAddress(e.target.value)}
        />
      </Label>
    </form>
  );
}

Note: Code snippets do not include styling details unless they are the focus of the exercise.

Copyright © 2022 Explore React