Function component life cycle hooks

We can invoke code to execute at certain points in a function component's life cycle. Let's explore this in our Confirm component, starting with when the component is first rendering, as follows:

  1. Let's add the highlighted lines of code just beneath where we define state:
const [cancelClickCount, setCancelClickCount] = React.useState(0);

React.useEffect(() => {
console.log("Confirm first rendering");
}, []);
  • We use React's useEffect function to hook into the component life cycle.
  • The function takes in an arrow function, which executes when the component is first rendered.
  • The function takes in a second parameter, which determines when our arrow function is called. This parameter is an array of values that, when changed, will cause the arrow function to be invoked. In our case, we pass in an empty array, so our arrow function will never be called after the first render.
  • If we now try the running app and open the console, we'll see Confirm first rendering only appears once.
  1. Let's remove the second parameter into useEffect now:
React.useEffect(() => {
console.log("Confirm rendering");
});

If we look at the running app and the console, we'll see Confirm rendering appear each time Confirm is rendered.

  1. Let's change this once again to the following:
React.useEffect(
() => {
console.log("open changed");
},
[props.open]
);

If we look at the running app and the console, we'll see open changed appear each time the Confirm component's open prop changes value.

  1. What about hooking into when a component is unmounted? Let's try the following:
React.useEffect(() => {
console.log("Confirm first rendering");
return () => {
console.log("Confirm unmounted");
};
}, []);

So, our arrow function can return a function that is executed when the component is unmounted.

  1. Our Confirm component doesn't currently unmount, so, in App.tsx, let's make this not render if the countdown reaches 0:
{this.state.countDown > 0 && (
<Confirm
...
/>
)}

If we look at the running app and the console, we'll see Confirm unmounted appear when the countdown reaches 0.

So, we can execute logic in function components when they are first rendered, when their props change, and when they are unmounted.

In the next section, we'll look at a method we can use to optimize function component rendering cycles.

This section on hooks is written on React v16.6.0. We will share updated codes when new version releases.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.150.163