React Holiday

#21: Abstracting

You probably screaming at me for not abstracting our pokemon-fetching, state-setting, transtiion-starting, suspense-coordinating onClick handler into an easy to remember function name.

That’s fair.

In a real app, we don’t want the liability of stringing four calls together ever click. But where do we draw the line?

I see one natural division:

  1. Functions that must be composed inside the component (the hooks)
  2. Functions that can be composed anywhere

First, the hooks… We can compose startTrasition and setPokemonResource into a single function. And because we’ve named the state updater setPokemonResource, we can use a more direct name like setPokemon for our composed event handler.

let setPokemon = (resource) =>
  startTransition(() => setPokemonResource(resource));

We can compose our suspense-coordinated fetch request anywhere. In a real-world app, this would likely happen in a module.

let getPokemon = (id) => suspensify(fetchPokemon(id));

That leaves with a very flexible and terse event handler:

() => setPokemon(getPokemon(id));

Now, you could boil it down to a single function, but this is plenty terse for me.

🐦 chantastic

P.S. Open up today’s StackBlitz demo. Add a “Previous” button. And maybe play with boiling these event handlers down even further.