//componentDidMount useEffect(() => { console.log("Behavior before the component is added to the DOM"); }, []); //componentDidUpdate useEffect(() => { console.log("Behavior when the component receives new state or props."); }); //Or useEffect(() => { console.log("Behavior when the value of 'stateName' changes."); }, [stateName]); //Or import React, { useEffect, useRef } from "react" const mounted = useRef() useEffect(() => { if (!mounted.current) { // do componentDidMount logic mounted.current = true } else { // do componentDidUpdate logic } }) //componentWillUnmount useEffect(() => { return () => { console.log("Behavior right before the component is removed from the DOM."); } }, []); //Putting it all together useEffect(() => { const intervalId = setInterval(() => { document.title = `Time is: ${new Date()}`; }, 1000); return () => { document.title = "Time stopped."; clearInterval(intervalId); } }, []);
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter