React Note — hooks lifecycle

利用 hooks 操作 react lifecycle 的方法: useEffect

Louis
3 min readAug 27, 2019

useEffect 把 componentDidMount, componentDidUpdate, componentWillUnmount 三個階段整合在一起

import React, { useState, useEffect } from 'react';

function Example() {
const [count, setCount] = useState(0);

useEffect(() => {
// Update the document title using the browser API
// componentDidMount && componentDidUpdate

return () => { // 若不調用 WillUnmount 可省略
// componentWillUnmount
}
});
// 預設不傳值, 每次變動都會重新呼叫 useEffect// [] 代表只會觸發這個 useEffect 一次
// [props.id] 代表僅在 props.id 變動時,才觸發 useEffect
// [count] 代表訂閱 state 的 count,意即 setCount 被調用後觸發改變的 count // 會進而也觸發 useEffect。
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}

useCallback ?

可以想成是一個 memoization 的 func 產生器,可帶入想訂閱什麼變數,變數改變時,也會重新產生帶入新參數的 func

useCallback(func(), [])// func() -> 要帶有 memoize 效果的function// [] -> 要訂閱什麼變數

實際用起來

把需要記憶的 function 在 useEffect 中調用。

import React, { useState, useEffect, useCallback } from 'react';

function Example() {
const [a, setA] = useState(0);
const [b, setB] = useState(0);
const doSomething = (a, b) => console.log(a, b);
const memoizedCallback = useCallback(
() => {
doSomething(a, b); // 利用會變動的 a, b 做一些奇怪的事情
},
[a, b],
);
useEffect(() => {
memoizedCallback();
}, [a, b]);

return (
<div>Sample</div>
);
}

--

--