summaryrefslogtreecommitdiff
path: root/src/utils.js
blob: c16c1b7c13cd0818a1748f98bf85c0674fa2e5e4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
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];
}