Member-only story
Create and Test Custom React Hooks
Setting up Next.js, TypeScript, Jest, and the React Testing Library to use and test our custom Hooks in React
React Hooks were introduced to the world at a React Conf in October 2018 and were later shipped in February 2019 as part of the React release 16.8.0
.
They are a game-changer since you no longer need to use React with ES6 classes anymore. Everything can happen through React Functional Components
.
React Hooks will replace how you manage property updates or how you manage your state. It is a more declarative and simpler approach. Creating custom Hooks is easy and intuitive.
A Bit of Context
Before React Hooks, logic was shared across components using the Render Props
method or through High Order Components
.
“The term ‘render prop’ refers to a technique for sharing code between React components using a prop whose value is a function.” — React’s documentation
These two approaches look hacky and produce a very messy JSX syntax. You could end up with “render props callback hell” or “wrapper hell”.
With React Hooks, we can reuse and embed the component’s logic in a better way. We can tightly couple related logic. Hooks are testable and composable.
In this article, we will be covering:
- Creating and configuring a basic app with Next.js + Typescript
- Refactoring the app to encapsulate some logic in a custom render Hook
- Using a library to test the newly created custom Hook
We have a lot to cover, so let’s begin!
Creating Our Next.js App
To run all the code, we will be creating a Next.js application.