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
}

  

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