import {useCallback, useRef, useState} from 'react'; import {shallowEqual} from "../utils/shallowEqual"; function useComparedState(initialState: any) { const [state, setState] = useState(initialState); const stateRef = useRef(initialState); // 更新state:只有當nextState與當前state產生變化時纔會觸發渲染,優化性能 const updateState = useCallback((nextState: any) => { if (shallowEqual(stateRef.current, nextState)) { return; } setState(nextState); }, []); return [state, updateState]; } export { useComparedState }