import { useState, useEffect } from 'react'; function getWindowDimensions() { const { innerWidth: width, innerHeight: height } = window; return { width, height }; } export function useWindowDimensions() { const [windowDimensions, setWindowDimensions] = useState(getWindowDimensions()); useEffect(() => { function handleResize() { setWindowDimensions(getWindowDimensions()); } window.addEventListener('resize', handleResize); return () => window.removeEventListener('resize', handleResize); }); return windowDimensions; } export function useDebounce(value, delay) { const [debouncedValue, setDebouncedValue] = useState(value); useEffect(() => { const handler = setTimeout(() => setDebouncedValue(value), delay); return () => clearTimeout(handler); }, [value, delay]); return debouncedValue; } export function GlobalState(initialValue) { this.value = initialValue; this.subscribers = []; this.getValue = () => this.value; this.setValue = (newState) => { if (this.getValue() === newState) return; this.value = newState; this.subscribers.forEach(subscriber => subscriber(this.value)); } this.subscribe = (itemToSubscribe) => { if (this.subscribers.indexOf(itemToSubscribe) > -1) return this.subscribers.push(itemToSubscribe); } this.unsubscribe = (itemToUnsubscribe) => { this.subscribers = this.subscribers.filter(subscriber => subscriber !== itemToUnsubscribe); } } export function useGlobalState(globalState) { const [, setState] = useState(); const state = globalState.getValue(); function reRender(newState) { setState({}); } useEffect(() => { globalState.subscribe(reRender); return () => globalState.unsubscribe(reRender); }) function setGlobalState(newState) { globalState.setValue(newState); } return [state, setGlobalState]; }