Skip to content

Instantly share code, notes, and snippets.

@dzrw
Last active December 13, 2018 19:26
Show Gist options
  • Save dzrw/5f03c169a4119a63abb785b1c1249656 to your computer and use it in GitHub Desktop.
Save dzrw/5f03c169a4119a63abb785b1c1249656 to your computer and use it in GitHub Desktop.
Hooks with Symbol keys
function StatusMessage() {
const HOOK_WINDOW_WIDTH = Symbol("window-width");
const HOOK_NETWORK_STATUS = Symbol("network-status");
const width = useWindowWidth(HOOK_WINDOW_WIDTH);
const isOnline = useNetworkStatus(HOOK_NETWORK_STATUS);
return (
<>
<p>Window width is {width}</p>
<p>You are {isOnline ? 'online' : 'offline'}</p>
</>
);
}
function useSubscription(key, subscribe, unsubscribe, getValue) {
const [state, setState] = useState(key, getValue()); // assumes a new useState(symbol, value) interface
useEffect(() => {
const handleChange = () => setState(key, getValue());
subscribe(handleChange);
return () => unsubscribe(handleChange);
});
return state;
}
function useWindowWidth(key) {
const width = useSubscription(key,
handler => window.addEventListener('resize', handler),
handler => window.removeEventListener('resize', handler),
() => window.innerWidth
);
return width;
}
function useNetworkStatus(key) {
const isOnline = useSubscription(key,
handler => {
window.addEventListener('online', handler);
window.addEventListener('offline', handler);
},
handler => {
window.removeEventListener('online', handler);
window.removeEventListener('offline', handler);
},
() => navigator.onLine
);
return isOnline;
}
@dzrw
Copy link
Author

dzrw commented Dec 13, 2018

In response to https://news.ycombinator.com/item?id=18669483, I'm not interested in a big debate. It just struck me that flaws #3 and #4 could've been more robust if they didn't include this refactoring error.

Overall, I like the hooks system far more than the class system.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment