useEffect

Side effects: Changes to the environment are side effects, such as modifying document.title and useEffect running after render. USES:

  • Used as componentDidMount,[] as the second argument
  • Used as componentDidUpdate to specify dependencies
  • Used as componentWillUnmount, via return

These three uses can exist at the same time

Simulation componentDidMount

import React, { useState, useEffect } from "react"; import ReactDOM from "react-dom"; function App() { const [n, setN] = useState(0); const onClick = () => { setN((i) => i + 1); }; UseEffect (() => {console.log(" execute on first render "); } []); return ( <div> n: {n} <button onClick={onClick}>+1</button> </div> ); } const rootElement = document.getElementById("root"); ReactDOM.render(<App />, rootElement);Copy the code

The second argument [] means that it is executed only on the first render, resulting in the following:

Simulation componentDidUpdate

import React, { useState, useEffect } from "react"; import ReactDOM from "react-dom"; function App() { const [n, setN] = useState(0); const onClick = () => { setN((i) => i + 1); }; UseEffect (() => {console.log("n changes when executed "); }, [n]); return ( <div> n: {n} <button onClick={onClick}>+1</button> </div> ); } const rootElement = document.getElementById("root"); ReactDOM.render(<App />, rootElement);Copy the code

N The command output is as follows:

Executed on behalf of any state change when no arguments are accepted

UseEffect (() => {console.log(' execute when any state changes ')})Copy the code

Simulation componentWillUnmount

UseEffect = componentWillUnmount useEffect = componentWillUnmount

import React, { useState, useEffect } from "react"; import ReactDOM from "react-dom"; const App = props => { const [childVisible,setChildVisible] = useState(true) const hide = () => { setChildVisible(false)  } const show = () => { setChildVisible(true) } return ( <div> {childVisible ? <button onClick={hide}>hide</button> : <button onClick={show}>show</button>} {childVisible ? <Child/> : Null} </div>)} const Child = (props) =>{useEffect(() =>{console.log(' rendered or changed ') return ()=>{ Console. log(' Child destroyed ')}}) return (<div> child </div>)} const rootElement = document.getelementById ("root"); ReactDOM.render(<App />, rootElement);Copy the code

When the child disappears from the page, it is destroyed.

UseEffect summary

// execute only on the first rendering: UseEffect (() = > {the console. The log (' first render executed after the words')}, []) / / n or m changes performed useEffect (() = > {the console. The log (' n change the value of + n.) Console. log('m changed, value '+m)},[n,m]) useEffect(()=>{console.log('n changed, value '+n) Console. log('m changed to '+m)}) // Return when the component is destroyedCopy the code