React hook useEffect is used in functional components to implement life-cycle callbacks. The Effect Hook lets you perform side effects in function components, but some people argue that DOM events might be a better place for that.
Source code viewer
import React, { useState, useEffect } from 'react'; export default function App() { const [windowWidth, setWindowWidth] = useState(window.innerWidth); const [count, setCount] = useState(() => 0); // Called every time the application renders. useEffect(() => { window.console.log('App Render Ran with useEffect'); }); // or simply skip the useEffect hook, this might get called more than once per render window.console.log('App Render Ran'); // Called every time the count changes. useEffect(() => { window.console.log('Changed Count: ' + count); }, [count]); // Runs on mount, because the dependencies never change. useEffect(() => { // You can use this to run queries. window.console.log('onMount event ran'); }, []); // An example of unmount. The return is also called before the effect is executed. useEffect(() => { // Unmount is in return of this mount effect. window.addEventListener('resize', handleResize); // Return is called on unmount and before effect is executed. return () => { // When you want to uso event listeners, you have to remove them on unmount. window.removeEventListener('resize', handleResize); }; }, []); const handleResize = () => { setWindowWidth(window.innerWidth); }; function increaseCount() { setCount((prevCount) => prevCount + 1); } return ( <div> <p>Window width: {windowWidth}px</p> <p>You clicked {count} times</p> <button onClick={increaseCount}> Click me </button> </div> ); }Programming Language: ECMAScript