UNPKG

@supunlakmal/hooks

Version:

A collection of reusable React hooks

39 lines 1.87 kB
import { useCallback, useState } from 'react'; import { useSyncedRef } from '../performance-optimization/useSyncedRef'; // Assuming this exists and works import { resolveHookState, } from '../../util/resolve-hook-state'; // Assuming this exists and works export function useMediatedState(initialState, mediator) { return useMediatedStateFn(initialState, mediator); } const useMediatedStateFn = (initialState, mediator) => { // Use useState directly with the initialState. useState handles functional initializers. const [state, setState] = useState(initialState); if (!mediator) { const setRawState = setState; return [state, setRawState]; } const mediatorRef = useSyncedRef(mediator); const setMediatedState = useCallback((value) => { const currentMediator = mediatorRef.current; if (currentMediator) { // If a mediator exists, then the type of State is never `undefined`. // Previous state is always `State` and never `undefined`. setState((previousState) => { // Previous state can never be undefined if there is a mediator, // because that means that the initial state must have been provided. const nextRawValue = resolveHookState(value, previousState); // Pass the raw value through the mediator to get the final state. return currentMediator(nextRawValue); }); } else { // No mediator exists, in this case RawState is State setState(value); } }, [mediatorRef]); // Return the current state and the mediated setter function. return [ state, // If no mediator, this will have type State | undefined, if there is mediator it is State setMediatedState, ]; }; //# sourceMappingURL=useMediatedState.js.map