In react life-cycle there are sets of method that being called when a component is being created and inserted to the DOM. Example when creating a component for the first time.
ComponentDidMount is called later when the componen is added to the DOM. Usually this function is used to run additional code after react has updated the DOM. (Eg, fetching external data, manual updating DOM mutation). This function has "side-effect"
When using a Function Component, react has similar method called useEffect
import React, { useState, useEffect } from'react';functionExample() {const [count,setCount] =useState(0);// Similar to componentDidMount and componentDidUpdate: useEffect(() => { // Update the document title using the browser API document.title =`You clicked ${count} times`; });return ( <div> <p>You clicked {count} times</p> <buttononClick={() =>setCount(count +1)}> Click me </button> </div> );}
This example shows function without cleanup method.
To create a effect that willbe cleanup after Unmount & every render,
functionFriendStatus(props) {const [isOnline,setIsOnline] =useState(null);useEffect(() => {functionhandleStatusChange(status) {setIsOnline(status.isOnline); }ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);// Specify how to clean up after this effect: returnfunctioncleanup() {ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange); }; });if (isOnline ===null) {return'Loading...'; }return isOnline ?'Online':'Offline';}
Only run when some data change
Running useEffect function for every render might not be good for performance. A second argument to the useEffect can be pass to only run the function when the listed data changed
useEffect(() => {document.title =`You clicked ${count} times`;}, [count]); // Only re-run the effect if count changes