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
}

  

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