Created
August 16, 2019 22:55
-
-
Save aleclarson/8300454b40c60968d0d6b62581c4e104 to your computer and use it in GitHub Desktop.
useSubscriber: Baked-in hook that lets subscribers notify React when data goes stale
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
import {useSubscriber} from 'react' | |
const MyComponent = (props) => { | |
// Get the current value of an observable | |
const value = props.value.get() | |
// Subscribe to the observable in the render phase | |
useSubscriber(forceUpdate => { | |
// This code runs immediately, instead of acting like "useEffect" | |
const unsub = props.value.subscribe(() => { | |
forceUpdate() // This tells React that the most recent render is stale | |
}) | |
// The returned function is called on dependency change or dismount | |
return unsub | |
}, deps) | |
return <h1>{value}</h1> | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment