React Function Component - Lifecycle

> (World Wide) Web - (W3|WWW) > Javascript (Js|ECMAScript) > React > Function Component

1 - About

lifecycle rendering in functional component are managed through effect

  • A mount run the body of the effect function (equivalent to a mount)
  • A unmount (called also cleanup) runs the function returned by the effect effection (equivalent to an unmount)
  • An update runs the mount and unmount (cleanup) code - Why ? As effects run for every render and not just once, React also cleans up effects from the previous render before running the effects next time. You can still skip this for perf reason.

For a class component, see class lifecycle method

Advertising

3 - Example

Demo:

  • A component with useEffect (that shows the mapping with the class lifecycle functions componentWillUnmount and componentDidMount).
index.jsx
function LifeCycle(props) {
 
    const [updateCount, setUpdateCount]= React.useState(0);
 
    React.useEffect(() => {
 
       console.log("Effect function has run         - same life-cycle as componentDidMount and componentDidUpdate");
 
        // Specify how to clean up after this effect:
          return function cleanup() {
             console.log("Cleanup Effect function has run - same life-cycle as componentWillUnmount");
        };
 
      });
 
    function handleClick(e) {
       setUpdateCount(updateCount+1);
    }
    return (
    <div>
        <h2>LifceCycle Component</h2>
        <p>The lifecycle Component sees {props.count} clicks and {updateCount} update count.</p>
 
        <p>An update mounts and unmounts (cleanup). Try it by clicking below</p>
       <button type="button" onClick={handleClick}>Update the component</button>
    </div>)
}
  • The App to mount and unmount the previous lifecycle component and triggers the effect and its return cleanup function
index.jsx
function App() {
 
   const [toggle, setToggle]=React.useState(false);
   const [count, setCount]=React.useState(0);
 
   function handleClick(e) {
     setToggle(toggle ? false : true);
     setCount(count+1);
   }
 
  let cycle = null;
  if (toggle) {
    cycle = <LifeCycle count={count}/>;
  } 
  return (
      <div>
        <h1>Mount/Unmount/Update Demo</h1>
        <button type="button" onClick={handleClick}>{toggle ? 'Unmount the lifecycle component' : 'Mount the lifecycle component'}</button>
        {cycle}
  </div>
  );
}
  • The classic Render to start the rendering. When <Lifecycle /> is passed to ReactDOM.render(), React calls the constructor of the Clock component, then calls the Clock component's render() method.
index.jsx
ReactDOM.render(
  <App />,
  document.getElementById('root')
);
index.html
<div id="root">
<!-- called the "root" DOM node because everything inside it will be managed by React DOM -->
</div>