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
}

  

posted on 2023-03-30 22:03  袜子破了  阅读(12)  评论(0编辑  收藏  举报