by Bob MacNeal, 3 Mar 2019
Hooks, from the Facebook engineering team, resolve a variety of issues and goofy workarounds in the React space (e.g., life-cycle methods, connecting to an application store, and passing stateful logic between components, to name a few).
Once comfortable with a few of the built-ins, I made a custom hook called
useAxiosGetItems. I plan to re-use this hook when I need to wire up GET requests in service-level functions. Indeed I use a slightly modified version of it in the sequel to this post Exploring React Hooks – 2.
The simple-hooks application demonstrates how I used hooks to back an interface consisting of four tabs meant to trigger the display of the following item lists:
Todos, Posts, Photos, and Users.
The item lists are fetched from the JSONPlaceholder API.
JSONPlaceholder, the self-proclaimed “Fake Online REST API for Testing and Prototyping”, is a low-resistance API that proved quite helpful in my prototyping to explore React hooks.
The main container in the simple-hooks prototype is the functional component Resource that includes navigational tabs and an ItemList component to display the item lists of the selected resource.
Note the use of useState (below). The useState invocations store the state of which UI tab was clicked (i.e., which resource type the user selected). The const initializes the default state to display TODOs. The second const initializes the default display fields for TODOs. The function handleSwitchTab responds to tab click events by updating the resource type and resource fields.
The syntax of useState is:
const [propertyName, setPropertyName] = useState(initial condition)
The custom hook I created uses the useEffect and useState hooks. The motivation behind the custom hook is to provide a generalized approach to making GET requests using the axios HTTP request library.
useAxiosGetItems is passed a URL. In this case, the URL points to various resources available in the JSONPlaceholder API.
The function makes an asynchronous request. It returns three entities at different times:
- loading – A boolean that is true until the HTTP request resolves, then changes to false. This loading variable allows for a progress indicator to be temporarily displayed in the UI while the request in in progress.
- listItems – When the request for the resource items resolves, an array of the requested resource (i.e., ToDos, Posts, Photos, or Users) is populated and returned with loading toggle to false.
- error – Should an error occur, an object including an HTTP return code and a descriptive message is sent back for display in the UI.
React hooks negate the need for confusing life-cycle methods and enable simple state management in functional components. They also reduce some of the boilerplate required by stateful class components.
Code for this prototype is available in the simple-hooks git repository.
Jump to Exploring React Hooks – 2.