A custom counter hook application is a simple web application that utilizes a custom hook called useCounter to update a counter value in the user interface. This application is the project for my second-semester examination at AltSchool Africa and I want to share the experience of creating this web application. Before I go any further, it'll be helpful if you understood what a hook is and what a custom hook is.
What is a hook?
Simply put, hooks are functions that let you “hook into” React state and lifecycle features from function components. Typically, functional components could not have state as well as other functionalities but the addition of react hooks provided that avenue. React took it a step further to allow the creation of custom hooks. Now, what is a custom hook?
What is a custom hook?
A custom hook is a JavaScript function that starts with the word "use" and can call other hooks. Building your own hooks lets you extract component logic into reusable functions.
The project
During the first version of this application, I created a simple user interface that allowed the users to start the counter, subtract from the counter and set a custom initial value for the counter. Other functionalities included in the application are:
- creating the custom counter hook
- creating the error boundary
- creating a 404 page
Custom counter hook
I used the useState hook and useRef hook to create my custom counter hook. Here is a snippet of the code.
404 page
A 404 page is an error message that displays for pages that don’t exist on a website. The 404 page can be customized to give website visitors a better experience. In this project, I created a user interface that gets displayed when a user tries to visit a page that doesn't exist.
Error Boundary
Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed.
Search Engine Optimization
To provide search engine optimization for my application, I used Next which provides great SEO features out of the box. Next utilizes server-side rendering and this only already provides a huge boost for search engine optimization.