1For componentDidMount
2useEffect(() => {
3 // Your code here
4}, []);
5
6For componentDidUpdate
7useEffect(() => {
8 // Your code here
9}, [yourDependency]);
10
11For componentWillUnmount
12useEffect(() => {
13 // componentWillUnmount
14 return () => {
15 // Your code here
16 }
17}, [yourDependency]);
18
1 useEffect(() => {
2 return () => {
3 console.log("cleaned up");
4 };
5 }, []);
1For componentDidMount
2useEffect(() => {
3 // Your code here
4}, []);
5
6For componentDidUpdate
7useEffect(() => {
8 // Your code here
9}, [yourDependency]);
10
11For componentWillUnmount
12useEffect(() => {
13 // componentWillUnmount
14 return () => {
15 // Your code here
16 }
17}, [yourDependency]);
1import React, { useEffect } from 'react';
2
3export const App: React.FC = () => {
4
5 useEffect(() => {
6
7 }, [/*Here can enter some value to call again the content inside useEffect*/])
8
9 return (
10 <div>Use Effect!</div>
11 );
12}
1import React, { useEffect, useState } from 'react';
2import ReactDOM from 'react-dom';
3
4function LifecycleDemo() {
5 // It takes a function
6 useEffect(() => {
7 // This gets called after every render, by default
8 // (the first one, and every one after that)
9 console.log('render!');
10
11 // If you want to implement componentWillUnmount,
12 // return a function from here, and React will call
13 // it prior to unmounting.
14 return () => console.log('unmounting...');
15 }, [ // dependencies to watch = leave blank to run once or you will get a stack overflow ]);
16
17 return "I'm a lifecycle demo";
18}
19
20function App() {
21 // Set up a piece of state, just so that we have
22 // a way to trigger a re-render.
23 const [random, setRandom] = useState(Math.random());
24
25 // Set up another piece of state to keep track of
26 // whether the LifecycleDemo is shown or hidden
27 const [mounted, setMounted] = useState(true);
28
29 // This function will change the random number,
30 // and trigger a re-render (in the console,
31 // you'll see a "render!" from LifecycleDemo)
32 const reRender = () => setRandom(Math.random());
33
34 // This function will unmount and re-mount the
35 // LifecycleDemo, so you can see its cleanup function
36 // being called.
37 const toggle = () => setMounted(!mounted);
38
39 return (
40 <>
41 <button onClick={reRender}>Re-render</button>
42 <button onClick={toggle}>Show/Hide LifecycleDemo</button>
43 {mounted && <LifecycleDemo/>}
44 </>
45 );
46}
47
48ReactDOM.render(<App/>, document.querySelector('#root'));
1import React, { useState, useEffect } from 'react';
2function Example() {
3 const [count, setCount] = useState(0);
4
5 // Similar to componentDidMount and componentDidUpdate:
6 useEffect(() => {
7 // Update the document title using the browser API
8 document.title = `You clicked ${count} times`;
9 });
10
11 );
12}