import { useEffect } from 'react'
function MyComponent() {
// Use useEffect hook:
useEffect(() => {
// Run something after every render.
}) // <= Omit the dependencies argument.
}
import { useEffect } from 'react';
function MyComponent() {
useEffect(() => {
// Runs ONCE after initial rendering
}, []);
}
import { useEffect, useState } from 'react';
function MyComponent({ prop }) {
const [state, setState] = useState('');
useEffect(() => {
// Runs ONCE after initial rendering
// and after every rendering ONLY IF `prop` or `state` changes
}, [prop, state]);
}
在這邊我們使用 JSONPlaceholder 提供的 FAKE API 做範例說明
fetch('https://jsonplaceholder.typicode.com/posts')
.then((response) => response.json())
.then((json) => console.log(json));
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then((response) => response.json())
.then((json) => console.log(json));
https://codepen.io/lala-lee-jobs/pen/GRdoNPe
https://codepen.io/lala-lee-jobs/pen/gOzPgbV
可避免React渲染方式和外部函式庫運作有衝突。
import {helperLibrary} from './HelperLibrary';
function App() {
const [data, setData] = useState(null);
useEffect = (() => {
helperLibrary.doSomething();
}, []);
// ...
}
https://codepen.io/lala-lee-jobs/pen/dyeMYOQ
import { useEffect, useState } from 'react';
function MyComponent({ someProp }) {
const [someState, setSomeState] = useState('');
const dependcyList = [someProp, someState];
useEffect(() => {
// Side-effect...
return function cleanup() {
// Side-effect cleanup...
};
}, [...dependcyList]);
// 如果第二個參數沒有指定 (undefined)
// 則表示每次 render 都會執行 cleanup
}
顯示畫面上按下的鍵盤文字 (這裡沒有指定 dependcyList,每次 render 都會執行 cleanup)
https://codepen.io/lala-lee-jobs/pen/QWrypeo
以秒計數,使用按鈕開始及暫停
(dependcyList 是 start,當 start 變更,render 後先做 cleanup,才做 effect function)
https://codepen.io/lala-lee-jobs/pen/GRdomZG
上面的以秒計數範例,使用 RxJS 的 interval 來做看看
https://codepen.io/lala-lee-jobs/pen/yLjebqO
透過實例,讓我們更清楚 useEffect 的使用情境,接下來會介紹 useEffect Tips,在未來的程式開發上靈活的使用 useEffect,會使用得專案程式易於開發及維護。
https://dmitripavlutin.com/react-useeffect-explanation/
https://codesandbox.io/embed/kw2b1?codemirror=1