-
-
Save jaredpalmer/1862cb13f9a65d85d2a8e411010c0a98 to your computer and use it in GitHub Desktop.
Prefetching in React
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 prefetch(getKey, getValue, getInitialValue, propName) { | |
const inFlight = new Set(); | |
const cache = new Map(); | |
return ChildComponent => { | |
return class extends React.Component { | |
state = {value: getInitialValue(this.props)}; | |
componentWillReceiveProps(nextProps) { | |
const key = getKey(nextProps); | |
if (cache.has(key)) { | |
// Use cached value | |
this.setState({value: cache.get(key)}); | |
} | |
} | |
async componentWillUpdate(nextProps) { | |
const key = getKey(nextProps); | |
if (cache.has(key) || inFlight.has(key)) { | |
// Request already in-flight | |
return; | |
} | |
inFlight.add(key); | |
const value = await getValue(key); | |
inFlight.delete(key); | |
cache.set(key, value); | |
this.setState({value}); | |
} | |
render() { | |
const props = {[propName]: this.state.value}; | |
return <ChildComponent {...props} />; | |
} | |
}; | |
}; | |
} | |
// Can use on multiple components, will share same internal cache | |
const prefetchThing = prefetch( | |
props => props.thingId, | |
thingId => fetch(`/api/thing/${thingId}`), | |
() => null, | |
'thing' | |
); | |
function View({thing}) { | |
if (user === null) { | |
return <LoadingSpinner />; | |
} | |
return <BlahBlahRealCode thing={thing} />; | |
} | |
export default prefetchThing(View); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello, I have made a small react utility(react-prefetcher) that can solve user-interaction based prefetching of resources.
Let me know how you like it - https://npmjs.com/package/react-prefetcher
Demo: https://manojvivek.github.io/react-prefetcher/
Repo: https://github.com/manojVivek/react-pefetcher