Last active
December 13, 2018 19:26
-
-
Save dzrw/5f03c169a4119a63abb785b1c1249656 to your computer and use it in GitHub Desktop.
Hooks with Symbol keys
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
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.