react useEnhancedState

import {useCallback, useRef, useState} from 'react';
import {shallowEqual} from "../utils/shallowEqual";

function isEquals(compare: any, current: any, nextState: any) {

    if (typeof nextState === "function") {
        return false;
    }

    if (!compare) {
        return false;
    }

    if (compare === 'equal') {
        return current === nextState;
    }

    if (compare === 'shallowEqual') {
        return shallowEqual(current, nextState);
    }

    if (typeof compare === "function") {
        return compare(current, nextState);
    }

    return false;
}


function useEnhancedState(initialState: any, compare: any = 'shallowEqual') {
    const [state, setState] = useState(initialState);

    // 与state数值是一致的,为避免产生新的updateState使用它与前一个值进行比较。
    const stateRef = useRef(initialState);

    // 永远指向最新的state
    const currentRef = useRef(initialState);
    currentRef.current = state;

    // 更新state:只有当nextState与当前state产生变化时才会触发渲染,优化性能
    const updateState = useCallback((nextState: any) => {
        currentRef.current = nextState; // 仅用来存储最新值

        if (isEquals(compare, stateRef.current, nextState)) {
            return;
        }

        stateRef.current = nextState;
        setState(nextState);

    }, []);


    // 在render之前,就能获取最新的state
    const getCurrent = useCallback(() => {
        return currentRef.current;
    }, []);

    return [state, updateState, getCurrent];
}


export {
    useEnhancedState
}

  

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