Created
March 4, 2022 23:02
-
-
Save pfernandez/e2ffb4693017b9e78d46df2d93537998 to your computer and use it in GitHub Desktop.
Store React component state and setters in a global object
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
if (APP.RUNTIME_ENVIRONMENT === RuntimeEnvironment.Development) { | |
// Create a global key-value store to keep references to all of our component | |
// state. | |
const store = {}; | |
(window as any).REACT_STORE = store; | |
const rawUseState = React.useState; | |
// @ts-ignore ~ TODO: Type this correctly. | |
React.useState = (initialState: any) => { | |
// Wrap useState so that we can store its results before returning them. | |
const result = rawUseState(initialState); | |
const [state, setState] = result; | |
// Create (but don't throw) an error, get the caller from the stack, and use | |
// it to generate a unique key for our store. Still looking for a better | |
// way. | |
const caller = new Error().stack?.split('at ')[2].split(' ')[0] || ''; | |
const { current } = useRef(uniqueId(caller)); | |
// Add a reference to the useState return values in the store under the | |
// unique component key. | |
if (!store[current]) { | |
store[current] = { state, setState }; | |
} | |
// Just logging, but notice that we can compare previous and next states | |
// here, which could allow performance enhancements. | |
if (state !== store[current].state) { | |
// tslint:disable-next-line no-console | |
console.log('Updating', current, 'to', state); | |
} | |
return result; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment