DEV Community

Cover image for A Step-by-Step Guide to UseReducer Custom Hooks with Increment, Decrement, Reset and SetValue Functions
Christian Ofoka
Christian Ofoka

Posted on • Updated on

A Step-by-Step Guide to UseReducer Custom Hooks with Increment, Decrement, Reset and SetValue Functions

My name is Christian Ikechukwu Ofoka and in December 2021, I made the brave decision to transition into technology. Taking the plunge and enrolling with Altschool Africa was a daring move, but one that I had to make. My second semester exam assessment for this program focused on a project of my choice which included...

  • Setup a custom counter hook with increment, decrement, reset, setValue functions with a valid UI

  • Implement a combination of states with a useReducer that
    implements a counter with the four evident features in the custom hook - increment, decrement, reset, setValue. Implement a page for the custom hook, useReducer, 404, and a page to test error boundary and good SEO.

Introduction

What is react?
React is a JavaScript library designed to facilitate the building of user interfaces. This library offers several advantages, such as reusability of components and a virtual DOM that enhances performance. Additionally, its declarative nature makes it simpler to create dynamic web applications. Moreover, React provides other benefits - click here for more information.

Custom Hooks have become an integral part of React development. They allow developers to easily create reusable logic that can be used across components, and make code more maintainable by reducing the amount of repetitive code written. One popular custom hook is useReducer, which allows for state management using reducers - a pattern commonly found in Redux applications.

What Is UseReducer?

The useReducer hook provided by React offers an alternative to the Redux framework for managing state in your React applications. Unlike the useState hook, which allows only local state management within a single component, useReducer provides global state management across all of your components.

Prerequisites
In order to comprehend my technical-write up, it is necessary that the reader possesses a basic understanding of web development technologies including HTML, CSS, the fundamentals of JavaScript ES6 and React.js Library.

As a React rookie, I was feeling overwhelmed and perplexed about how to begin. The more I pondered the problem, the more confused I became. But then, as is usually the case with any conundrum, I decided to turn to the internet for answers; watching tutorials and videos helped me get up to speed. Additionally, since previously completing an assignment on something similar gave me a headstart in this new venture.

This was my first time using the online ide codesandbox, and I made a few things before I realized that I had forgotten to save. As a result, I ended up having to rewrite the same code multiple times before it clicked. A friendly reminder: always remember to go to the File tab and click 'Save All'!

HOME PAGE

I wanted something nice from my wirefirming but implementing it what a problem, so i decided to have my photo on the front page (that was my best picture 2022) to make the picture more about me than keeping it blank and below it was a link to my github profile.

Image description

import { Link } from "@mui/material";
import React from "react-dom";
import image from "../Components/chris.png";
import Typed from "react-typed";
import "../styles.css";
const Homepage = () => {
  return (
    <div className="chris">
      <h1 className="There">
        Hi There!
        <br />
        <Typed
          strings={["Welcome to my Website", "My name is Christian Ofoka"]}
          typeSpeed={20}
        />{" "}
      </h1>
      <span>
        <h3> I'm suck at maths but one equation I never get wrong 👉</h3>
        <img src={image} alt="chris" />
      </span>
      <div>
        <a href="https://github.com/Codename-Kris" target="_blank">
          <button> Get into my profile </button>
        </a>
      </div>
    </div>
  );
};
export default Homepage;
Enter fullscreen mode Exit fullscreen mode

FUNCTIONS

The useReducer Hook enabled the adjustment of the count, increasing, decreasing or setting it. The hook takes a state and its dispatch as its value, with a reducer function I had created on another page along with an initialValue of count set to 0.
This is what my home page code look like:

import { useState } from "react";

On the customhook page, you will find functions such as decrement, increment, reset and setvalues.

import React from "react-dom";
import { useState } from "react";
import "../styles.css";

const Costhook = () => {
  const [counter, setCounter] = useState(0);
  const [input, setInput] = useState(0);

  const increment = (event) => {
    event.preventDefault();
    setCounter(counter + 1);
  };

  const decrement = (event) => {
    event.preventDefault();
    setCounter(counter - 1);
  };

  const reset = (event) => {
    event.preventDefault();
    setCounter(counter * 0);
  };

  const setvalue = (event) => {
    event.preventDefault();
    setCounter(input);
  };

  const handleChange = (event) => {
    setInput(event.target.value);
  };

  return (
    <div>
      <h1>{counter}</h1>
      <input className= "input" type="number" value={input} onChange={handleChange} />
      <br />
      <button className="incrementBtn" onClick={increment}>
        {" "}
        Increment 
      </button>

      <button className="decrementBtn" onClick={decrement}>
        {" "}
       Decrement
      </button>
      <br />
      <button className= "setBtn" onClick={setvalue}> setvalue</button>
      <button className="resetBtn" onClick={reset}>
        {" "}
        reset
      </button>
    </div>
  );
};

export default Costhook;

Enter fullscreen mode Exit fullscreen mode

Image description
At this juncture, I was feeling invigorated as the progress I was making far outweighed my initial apprehensions. My UI still wasn't looking great, but that was the least of my concerns as there were still a lot of elements to implement. Implementing error boundaries proved to be a cinch - all that was required of me was typing npm install react-error-boundary in my terminal and creating a fallback component in case of any errors - and that's it requires

Most of the npm where installed at the right corner of the page for example like:

`import React from "react-dom";
import image from "../Components/chris.png";
import Typed from "react-typed";
import "../styles.css";`
Enter fullscreen mode Exit fullscreen mode

I proceeded to the 404 page, which is a response code indicating that the webpage requested by a client cannot be located. This is part of the Hypertext Transfer Protocol's set of response codes. The error message can appear as "404 Error," "404 Page Not Found" or "The requested URL was not found."

Image description

These are the following step you should take when Setup a custom counter hook with increment, decrement, reset, setValue functions with a valid UI and Implement a combination of states with a useReducer that
implements a counter with the four evident features in the custom hook - increment, decrement, reset, setValue. Implement a page for the custom hook, useReducer, 404, and a page to test error boundary and good SEO.

Install dependencies
At the lower left of your terminal screen, make sure to use npm install to build the dependencies of the project.

Implementation of seo
Search engine optimization (SEO) is an essential part of any successful website. It helps ensure that your content reaches its intended audience, as well as increasing the visibility and ranking of your site in search engines like Google and Bing. If you're building a React-based website or application, then it's important to consider how SEO can be implemented into this framework.

One of the most basic aspects of SEO is creating appropriate meta tags for each page on your site. This includes things like title tags, description tags, image alt attributes etc., which provide information about the contents or purpose of a given page to both users and search engines alike. This is the way I implemented SEO, as demonstrated below:

`<Helmet>
        <meta charSet="utf-8" />
        <title>2nd Semester Exam</title>
        <link rel="canonical" href="https://lbisjr.csb.app/" />
      </Helmet>`

Enter fullscreen mode Exit fullscreen mode

Conclusion

in this article, we created a React application with counter app that can function increment, decrement, setvalue and reset.

this is the source code hereand the live link is located here . Thank you for reading!

Thank you as well to the Altschool Africa team for a job well done. @oluwasetemi @jerryuke @tabitha @adedejioshinojo

Top comments (0)