- state는 리렌더링 이전에 값이 바뀌지 않으므로, 이를 보완하기 위해 ref를 함께 사용하여 래핑
import { useEffect, useRef, useState } from 'react';
export const useRealtimeState = <T extends any>(initialState?: T) => {
const [state, setState] = useState<T>(() => {
return initialState as T;
});
const stateRef = useRef<T>(initialState);
const set = (value: T) => {
stateRef.current = value;
setState(value);
};
const get = () => stateRef.current;
// useEffect(() => {
// stateRef.current = state;
// }, [state]);
return [state, stateRef, set, get] as const;
};