Last active
February 18, 2022 03:51
-
-
Save drodsou/b947eb192d18ac8d3a57aabba006c3ca to your computer and use it in GitHub Desktop.
Synchronous useState (React hooks)
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 {useState, useRef} from 'react'; | |
/** | |
* @description provides a sync useState like | |
* with a plain mutable object as state and a separate render function | |
* to trigger react rerender when wanted. | |
* @example: | |
* const [state, renderState] = usePlainState({...initialstate}); // const is important, not accidentally overwrite the whole object and lose the 'ref' | |
* state.prop = state.prop++; | |
* ... | |
* renderState(); // or as well: renderState({changedProp:newValue}); // will merge state, not replace it | |
* | |
*/ | |
export default function usePlainState (initialState) { | |
const plainState = useRef(initialState).current; | |
let [_,setReactState] = useState(false); | |
return [ | |
plainState, // st | |
(newPlainState)=>{ // renderSt() | |
if (newPlainState) { | |
Object.assign(plainState, newPlainState); // object.assign no not substitute the plainState object | |
} | |
setReactState(reactState=>!reactState) // forceUpdate | |
} | |
]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment