Skip to content

Instantly share code, notes, and snippets.

@Armster15
Created July 7, 2024 01:10
Show Gist options
  • Save Armster15/83784f94a2fd82ee3192eb9021235f56 to your computer and use it in GitHub Desktop.
Save Armster15/83784f94a2fd82ee3192eb9021235f56 to your computer and use it in GitHub Desktop.
React state that can be updated imperatively
import { useEffect, useState } from 'react';
export const createImperativeState = <State>(
initialState: State | (() => State)
) => {
let listeners: Array<(state: State) => void> = [];
let memoryState: State =
initialState instanceof Function ? initialState() : initialState;
function updateState(newState: State | ((prevState: State) => State)) {
memoryState =
newState instanceof Function ? newState(memoryState) : newState;
for (const listener of listeners) {
listener(memoryState);
}
}
function useStore(): State {
const [state, setState] = useState<State>(memoryState);
useEffect(() => {
listeners.push(setState);
return () => {
const index = listeners.indexOf(setState);
if (index > -1) {
listeners.splice(index, 1);
}
};
}, [setState]);
return state;
}
return { useStore, updateState };
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment