react useCurrentState

import {useCallback, useRef, useState} from 'react';


function useCurrentState(initialState: any, compare?: any) {
    const [state, setState] = useState(initialState);
    const ref = useRef(initialState);
    ref.current = state;

    const updateState = useCallback((nextState: any) => {
        ref.current = nextState;
        setState(nextState);
    }, []);


    const getCurrent = useCallback(() => {
        return ref.current;
    }, []);

    return [state, updateState, getCurrent]
}


function useCurrentState2(initialState: any = {}, compare?: any) {
    const [state, setState] = useState(initialState);
    const ref = useRef(initialState);
    ref.current = state;

    const updateState = useCallback((nextState0: any) => {
        const nextState = {...ref.current, ...nextState0};
        ref.current = nextState;
        setState(nextState);
    }, []);

    const getCurrent = useCallback(() => {
        return ref.current;
    }, []);

    return [state, updateState, getCurrent]
}


export {
    useCurrentState,
    useCurrentState2
}
  

  

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