Use React hooks to get of the zombie spinner for good

Johannes Brodwall
2 min readNov 29, 2020

--

With a custom useLoader hook, you can ensure that loading of data from your backend has consistent loading and error behavior.

If you have ever created a web page you have surely committed the most common sin of web pages: You start fetching data from the backend and show a spinner to the user. But after an error occurs, you forget to stop the spinner (or display the error message!) and the user sits and waits forever for a spinner that never stops spinning.

The key to effective development is to solve the same problem in the same simple way every time so you know that if you have fixed the spinner and error message one place, it will work correctly everywhere.

In version 16.8, React introduced the concept of hooks, which allows you to use functional components for many more scenarios. Hooks also makes it possible to create advanced reusable functionality.

In this article, we will examine one such custom hook, which I’ve called `useLoader`.

This is the result we’re aiming for:

When loadTodo is fetching data from the backend, the view looks like this:

If an error occurs, the view looks like this:

In this bit of code, the useLoader, spinner and error display is perfectly reusable between each component. The specific part for this component is how to load the data (loadTodoList) and how to display the results.

useLoader is implemented by building on the existing React hooks useEffect and useState. A simplified implementation looks like this:

useLoader.ts — a simplied custom hook for loading

The hook uses three state variables to hold the loading state, the returned data and the error, if any. It uses useEffect to call the loading function asynchronously. It returns the state variables plus the reload function to the caller so they can be used to display the results.

Creating a custom useLoader hook has enabled me to build applications where I can be sure that every loading has a spinner and every error is displayed in a consistent way to the user. The clean React 16.8 makes my code clearer and to-the-point.

You can explore a working example at https://codesandbox.io/s/loader-demo-df9nc?file=/src/App.tsx

--

--