react useComparedState

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
}

  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章