Skip to content

Introducing react-create-view

react-create-view provides a utility to standardize creating views that go through different states:loadingsuccessemptyerror.

View is just a generic term for a UI that renders some stuff.

We’re used to building a view that makes an api call and can render something different depending if api call is loading, a success, errors out, or provides an empty list.

Like many of you, I work on a team and each team member handles this use case differently. The goal here is to standardize how a team builds these sort of views.

The createView utility helps change code from something like this:

Introducing react-create-view
code from my teams repo to build a view for user to manage their accounts addresses

to something like this:

Introducing react-create-view
code using the createView utility

You have to use some imagination, but you may be able to tell which code example is easier to comprehend. I mean both examples technically work in the end. They render a different view based on the current state (successloadingemptyerror). However the first example requires a bit more mental jujitsu as there is a combo of if conditions and the ternary operator to determine which UI to render.

The createView utility however cleanly breaks these UI conditions into definitive components.

Essentially, you provide some TS generic types to createView which represent a SuccessModel, FailureModel, LoadingModel, or EmptyModel and write the component code for each state of the view where the props correspond to the provided model.

How do we provide the models to the view? The answer is a hook.

Use the provided ViewModelProps type to build your hook. The ViewModelProps type is a TS union with a status enum and a model for each possible status. When the status is success, the Success component in createView is rendered and so on.

Introducing react-create-view
ViewModelProps type
Introducing react-create-view
using the ViewModelProps type

Once you have your custom ViewModelProps type, set it as the return value of a hook.

Introducing react-create-view
creating hook to power the view

After that combine the hook and the view returned from createView utility and viola

Introducing react-create-view
build a component from createView utility and hook

This also helps developers separate their View/UI from the business logic.

The view can easily be tested in something like Storybook and use mock data, while the hook can be responsible for actual business logic.

Power your hook with something like react-query to handle api call states and you’re good to go.

The last thing to note is to create your models based on what the UI requires, not what the API supplies! The client should own its models, not the API. This way when API v2 comes out, you are not changing any logic in the view layer, but in the business logic layer or the hook.