Created
July 7, 2024 01:10
-
-
Save Armster15/83784f94a2fd82ee3192eb9021235f56 to your computer and use it in GitHub Desktop.
React state that can be updated imperatively
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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