Skip to content

Instantly share code, notes, and snippets.

@kentcdodds
Last active February 6, 2022 05:29
Show Gist options
  • Save kentcdodds/2510249a3fc5c9dce82ccee80396fc6a to your computer and use it in GitHub Desktop.
Save kentcdodds/2510249a3fc5c9dce82ccee80396fc6a to your computer and use it in GitHub Desktop.
// NOTE: you will NOT write code like this when using suspense
// instead, you'll use react-cache (not yet officially published)
// it'll handle things like pre-loading, handling rapid re-renders, etc.
const cache = {}
function FetchPokemon({pokemonName}) {
const pokemon = cache[pokemonName]
if (!pokemon) {
const promise = fetchPokemon(pokemonName).then(
pokemon => (cache[pokemonName] = pokemon),
)
// the placeholder will catch this and
// rerender when the promise resolves
throw promise
}
return <pre>{JSON.stringify(pokemon || 'Unknown', null, 2)}</pre>
}
function PokemonInfo({pokemonName}) {
return (
<React.Placeholder fallback="loading pokemon data...">
<FetchPokemon pokemonName={pokemonName} />
</React.Placeholder>
)
}
// Usage: <PokemonInfo pokemonName="Pikachu" />
// Cool right? These are all function components!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment