Skip to content

Instantly share code, notes, and snippets.

@joduplessis
Created September 11, 2023 07:30
Show Gist options
  • Save joduplessis/adcca4098ae0ebcd719eb9e816893c5a to your computer and use it in GitHub Desktop.
Save joduplessis/adcca4098ae0ebcd719eb9e816893c5a to your computer and use it in GitHub Desktop.
Stupid simple global state management using React Hooks.
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