TECHNICAL WRITE-UP: CUSTOM COUNTER HOOK IMPLEMENTATION WITH REACT.
Published: 2024-02-07 22:05:07

TECHNICAL WRITE-UP: CUSTOM COUNTER HOOK IMPLEMENTATION WITH REACT.
INTRODUCTION
The custom counter hook is a react hook that allows developer to quickly and easily create counter Application which has the increment, decrement, reset and the update-Value features. Additional features that can be added to this custom hook application is the react router with which user can navigate to the different components of the application from the home page and back to the homepage, the 404 page which would be displayed incase the user type a wrong url and lastly is the Error boundary component that helps to catch the JavaScript error in the child component’s tree, it then displays a fallback UI in place of the component that crashed. 
This article will work us through the steps involved in implanting the above-mentioned functionalities using react custom hooks approach.
INSTALLATION OF THE REACT APPLICATION
In implementing react custom hooks, the first thing is to install react Application using the create react app approach.
In this approach, you run the following command in the terminal of the Visual Studio Code and the react Application would be created
First step in creating react App is 
npx create-react-app (counter App.)
The counter App inside the bracket is the name of the project that would be displayed after the App has been created. 
Second step. 
We cd in to the counter App i.e. the name of the Application.
Third step. 
We run the command npm start.
With the above command line, the react Application would be installed. 
INSTALLATION OF THE DEPENDENCIES
After the react Application has been created, the following dependencies would be installed.
•	The react router
•	The react-router-dom
•	The react-error-boundary
we install the above dependencies by running the command, 
•	npm install react-router 
•	npm install react-router-dom
•	npm install react-error-boundary.

CREATING REACT HOOK FOLDER AND FILE
After installing the dependencies, we create a hook folder under the src folder where react hooks file components would be stored.
In the hook folder we create a Usecount.js file which will handle all the functions to create the counter Application. Such functions include;
The increment 
The decrement 
The reset
The set values 
First, we import useState from react using the syntax below;
Import {useState} from react. 
 From the code given below, the useCount is the global function that houses the functions to be implemented (increment, decrement, reset and updateValue) in the counter Application. 
While implementing the increment and the decrement function, we update the state based on the previous state (i.e. useState(0)), using the useState call back function, also while  implementing the reset function, we retain the previous/default state of useState i.e useState(0) and while implementing the updateValue function, we set a new value as parameter in the function and call that value inside the function by changing the default useState  to the preferred value.
The final step in this useState.js component is to return the functions. The code use for the implementation is give blow.
import {useState} from "react";

export default function Usecount(){
    const[count, setCount]=useState(0);

    const increment=()=>{
        setCount((prev)=>++prev)
    };

    const decrement=()=>{
        setCount((prev)=>--prev)
    };

    const reset=()=>{
        setCount(0)
    };

    const updateValue=(value)=>{
        setCount(value)
    };

    return{count, increment, decrement, reset, updateValue}

};


CREATING THE ROUTER FOLDER AND COMPONENTS
The next step is to create a route folder which is basically used to move from one page to the other within the application. In the route folder we create the root.jsx file and the counter.jsx component. The root.jsx component will be the home page for the application and from there we can navigate to the other functional pages of the  Application and back to the hompage. The root.jsx also contains the react Link tag used to route to other pages of the application from the home page. In order to use the react Link tag in the home page, it must be imported from the react router dom.
Also, in the root.jsx file(hom epage), a react Link tag is created in order to test if the 404 page is working perfectly. In order to implement this, we create an invalid url (i.e. the url that does not exist within the react Link tag ), and once the link is clicked we would redirected to the 404 page.
THE ERROR BOUNDARY.
For the error boundary to work and be tested, it must be imported in the root component(homepage) and the Testerror component must be imported and rendered as well. Also the react error boundary element is wrapped around the tags in the root component(homepage) and it accepts a fall back message which is what would be displayed whenever the error is encountered within the application.  
The code for the implementation of the root.jsx component is given below;

import { Link } from "react-router-dom";
 import TextError from "../TestError";
 import { ErrorBoundary } from "react-error-boundary";
 import './root.css';

 function Root(){
    return(
        <div className="container">
            <ErrorBoundary fallback={<h1 >An Error just occured</h1>}>
            <h1 id="title" className="container">This is the home page! you are welcome.</h1>

            <p className="container">kindly proceed to the <Link to="/counter" className="error-link">counter App</Link> - my second semester project in order to explore how it works</p>

          <TextError/>  

            <p className="container">You can explore our 404 page by clicking on the link below</p>

            <Link to="/does not exist" className="error-link">Explore 404 page</Link>
            </ErrorBoundary>

    
        </div>
    );
};

export default Root;

THE COUNTER.JSX FILE
In the counter.jsx component, the functions contained in the useState hooks are destructured so that we can have access to them in the counter.jsx component. These functions from the react custom hooks are then called inside the buttons in the counter.jsx component. In order to implement the updateValue function declared in the custom hooks, Two other functions in the counter.jsx function are implemented, one of the function was called in the input tag of the updateValue while the other was called on the button tag of the updateValue-  the button tag onclicked would  update the counter application base on the value set in the input field.
There is also a react Link tag in the counter.jsx component used to navigate back to the home page. 
The code for the implementation of counter.jsx component  is given below
import { useState } from "react";
import Usecount from "../Hooks/useCount";
import { Link } from "react-router-dom";
import './counter.css';

function Counter(){
const {count, increment, decrement, reset, updateValue}=Usecount()

const[updateCount, setUpdateCount]=useState("")

const handleChange=(event)=>{
    // setUpdateCount(event.target.value);
     (event.target.value)=updateCount

};

const handleClick=()=>{
    updateValue(+updateCount);
    setUpdateCount("")
}

return(
    <div className="btn">
        <div className="container">
        <h1 id="title">Hey! Welcome to Counter-App page</h1>
        <h2 id="current">current Value : {count}</h2>
        <button onClick={increment} id="incr" className="btn-App" >increment</button>
    
        <button onClick={decrement} id="decr" className="btn-App">decrement</button> 
        
        <button onClick={reset} id="res" className="btn-App">reset</button> 
        
        <button onClick={handleClick} id="update"> setValue</button>
        <input type="number" value={updateCount} onChange={handleChange}/>
        
         <h2><Link to="/" className="btn-App" id="home">Home Page</Link></h2>
         </div>
    </div>
)

}

export default Counter;

THE App.jsx COMPONENT
The next step is to implement the different routes that will link to the different pages using the App.jsx component. 
First of all, we import createBrowserRouter and the RouterProvider from "react-router-dom" in to the App.jsx component. The different folder we intend to navigate to has to be imported too. The route is the folder that contains the root component and the counter component. the root component is the homepage while the counter.jsx component is the page where the main operations of the Counter application is performed. 
First thing  to do in the App.jsx after importing the necessary file is to initialize the route by creating a function that takes an array of object. Inside this function we create path for the homepage(root.jsx) and the main page (counter.jsx)). Then we render the router in the return statement because it contains the all the paths we intend to navigate to. In rendering the router in the return statement, we wrap the router with the RouterProvider tag we already imported.it must be noted that, the value in front of the path would be used in the url to route to the desired page, most times, we use the name of the component for easy identification.

Link takes a to props which contains the path one intend to route to.
In order for us to handle error by specific declaration in the app.jsx file, we create another route in form of a child element in the app.jsx file. This would be able to handle all errors relating to wrong url in the application. This approach is usually referred to as the wildcard route and denoted by an asterisk /*/ which handle the global error within the application 
import { createBrowserRouter, RouterProvider } from "react-router-dom";
import './App.css';
import  Root from "./routes/root";
import Counter from "./routes/counter"

function App() {

  //initialization of the router
  const router=createBrowserRouter([
    {
    // home page initialization
    path: "/",
    element:<Root/>,
  
  },
  {
    // counter page initialization
    path:"/counter",
    element:<Counter/>
  },

  {
    // error page initialization
    path:"*",
    element:<h1>404 page,  provide valid url </h1>,
    
  },
]);
  return (
    <div className="App">
      <RouterProvider router={router}></RouterProvider>
    </div>
  );
}

export default App;


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.
In order to implement the error boundary, we create another component called TestError. Inside the component, we import a useState from react and set the initial state to false. In order to test if the error boundary works perfectly, we create a button in the return statement so that onclick of that button we should get the error statement, by calling the testError function and changing the initial useState from false to true. Even though there is not error in the application, error message would be seen. For the error boundary to work, it must be imported in the root component(homepage)  and the Testerror component must be imported and rendered as well. Also the react error boundary element is wrapped around the elements in the root component(homepage) and it accepts a fall back message which is what would be displayed when ever the error is encountered within the application  
import { useState } from "react";
import './App.css';

function TextError(){
    const[hasError, setHasError]=useState(false);
    
    if(hasError){
        throw new Error("An Error is found");
    };

    return(
        <div>
            <h3>please comfirm our Error Boundary Here</h3>
            <button onClick={()=>setHasError(true)} className="boundary">Checking Error Boundary</button>
        </div>
    )
};

export default TextError;

CONCLUSION
The above explanation gives a simple step-by-step way of implementing the react custom hook to build counter Application that has the increase, decrease, reset and updateValue features.