useEffect:dom完成渲染后執行
- 不傳參數,每次都會執行
傳空的依賴[]
,只會執行一次
有依賴,依賴項變化會執行
useEffect實現動畫效果
import { useEffect, useRef, useState } from "react"const App = () => {const [, setCount] = useState({})const refDiv = useRef()useEffect(() => {console.log('執行useEffect')setTimeout(() => {refDiv.current.style.transform = 'translateX(150px)'refDiv.current.style.transition = 'all .9s'}, 1000)// 清理函數 要顯示返回的動畫,上面的函數應延遲一段執行// 否則太快回到150px位置,看不到效果return () => {console.log('執行清理函數')refDiv.current.style.transform = 'translateX(0px)'refDiv.current.style.transition = 'all .9s'}})const styleObj = {width: '50px',height: '50px',background: 'skyblue'}return (<><div style={styleObj} ref={refDiv}></div><button onClick={() => setCount({})}>click</button></>)
}
export default App
useLayoutEffect
- 和
componentDidMount
和componentDidUpdate
調用階段一致
import { useEffect, useLayoutEffect, useRef, useState } from "react"const App = () => {const [, setCount] = useState({})const refDiv = useRef()useLayoutEffect(() => {console.log('useLayoutEffect渲染前執行')// 若不延遲 在useLayoutEffect看不到移動,而是初始就在150的位置setTimeout(() => {refDiv.current.style.transform = 'translateX(150px)'refDiv.current.style.transition = 'all .9s'}, 1000)return () => {console.log('執行清理函數')refDiv.current.style.transform = 'translateX(0px)'refDiv.current.style.transition = 'all .9s'}})const styleObj = {width: '50px',height: '50px',background: 'skyblue'}return (<><div style={styleObj} ref={refDiv}></div><button onClick={() => setCount({})}>click</button></>)
}
export default App
useDebugValue
- 用于在React開發者工具中顯示自定義hook的標簽
自定義hook
import { useEffect, useState } from 'react'
// 自定義hook
const useCount = params => {const [count, setCount] = useState(0)useEffect(() => {document.title = `第${count}次點擊`})return [count, setCount]
}
const Foo = () => {const [count, setCount] = useCount(0)useEffect(() => {console.log('Foo useEffect')})return (<><h1>{count}</h1><button onClick={() => setCount(count + 1)}>click</button></>)
}
const App = () => {return <Foo />
}
export default App