Skip to content

Instantly share code, notes, and snippets.

@drodsou
Last active February 18, 2022 03:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drodsou/b947eb192d18ac8d3a57aabba006c3ca to your computer and use it in GitHub Desktop.
Save drodsou/b947eb192d18ac8d3a57aabba006c3ca to your computer and use it in GitHub Desktop.
Synchronous useState (React hooks)
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