Skip to content

Instantly share code, notes, and snippets.

@aleclarson
Created August 16, 2019 22:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aleclarson/8300454b40c60968d0d6b62581c4e104 to your computer and use it in GitHub Desktop.
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
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