Created
September 11, 2023 07:30
-
-
Save joduplessis/adcca4098ae0ebcd719eb9e816893c5a to your computer and use it in GitHub Desktop.
Stupid simple global state management using 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 React, { useState, useEffect } from 'react' | |
let state = { user: { name: '' } } | |
export const dispatch = (data) => { | |
const { namespace, ...rest } = data | |
state = { ...state, ...rest } | |
window.dispatchEvent(new CustomEvent(namespace, { detail: data })) | |
} | |
export const getState = (namespace) => { | |
const [_, render] = useState(new Date()) | |
const handler = (data) => render(new Date()) | |
useEffect(() => { | |
window.addEventListener(namespace, handler) | |
return () => window.removeEventListener(namespace, handler) | |
}) | |
return state | |
} | |
/** | |
example: | |
1) listen for global state changes | |
2) dispatch global state updates | |
export function App(props) { | |
const { user: { name } } = getState('user') | |
const onClick = (e) => dispatch({ namespace: 'user', user: { name: 'John' } }) | |
return <button onClick={onClick}>{name || 'Update Name'}</button> | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment