DEV Community

Cover image for Setting up a React Counter Custom Hook with a combination of State.
Mary Sule
Mary Sule

Posted on

Setting up a React Counter Custom Hook with a combination of State.

This is something some persons might overlook thinking it's easier because it has to do with a counter. But yeah, they might be right.
Let me share a bit of my journey..
I applied for Altschool of engineering frontend track late 2021 and got in by 2022. It has been an amazing journey thus far with a lot of experiences and learning. In second semester I was taught React which is the most popular frontend framework. After 2 months of in-depth learning, the semester was wrapped up with an examination to test our knowledge and understanding of what we have been taught in React. It was a total of four questions to answer one. I was skeptical on which to do but then again, I started having issues with my laptop and was almost given up but then I had t remind myself of how I really needed this..
Okay, enough of my story...would share more in my next article but for now, let's stick to the topic.

React Custom hook is an important aspect of react. It's actually one of the uniqueness of react. which is reusability. Rather than rewriting same code on multiple components with common stateful logic, It is easier to put the code in a custom hook and reuse it. It is used to add special and unique functionalities to react applications.
Image description
The instructions given for the exam project was to implement the following:

  • Create a custom counter with increment, decrement, reset,
    setValue functions with a valid UI component

  • Implementation of combination of State with useReducer

  • A 404 page

  • A page for Error Boundary

  • Test for a good SEO

First I installed my react app using

npm install vite following the documentation from https://vitejs.dev/guide/. After installation, I went ahead and created ny react components based on the requirement.

import { useState } from "react";

export default function useCounter(initialValue = 0) {
  const [count, setCount] = useState(initialValue);
  function increase() {
    setCount((prevCount) => prevCount + 1);
  }
  function decrease() {
    setCount((prevCount) => prevCount - 1);
  }
  function reset() {
    setCount(0);
  }
  function setValue(e) {
    let num = Number(e.target.value);

    setCount(num);
  }
  return { count, increase, decrease, reset, setValue };
}


Enter fullscreen mode Exit fullscreen mode

The useState is used in functional components to declare state variables as this.state is used in class component. setState is a way of preserving the state variable.
After declaring the state variable we initialized our variable which is the count. It could be any name depending on what you are working on. A name similar to your project should be considered for better readability. A set value of 0 was initialized which will be the default counter number.
The custom hook I created useCounter was then imported into my Counter Component which contains the increment, decrement and reset buttons.

UseReducer

  The useReducer is very similar to useState. It is also a react hook. It can only be called at the top of a component. It returns a dispatch function that allows to update the state to a different value and trigger a re-render.
Enter fullscreen mode Exit fullscreen mode
import { useReducer } from "react";

function ReducerCounter() {


  function setValue(value) {
    let num = Number(value);

    return num;
  }
  function reducer(count, action) {
    switch (action.type) {
      case "set_value":
        return setValue(action.payload);
      case "increase":
        return ++count;
      case "decrease":
        return --count;
      case "reset":
        return 0;
      default:
        return count;
    }
  }
  function inputHandler(e) {
    dispatch({
      type: "set_value",
      payload: e.target.value,
    })
  }
  const [count, dispatch] = useReducer(reducer, 0);

  return (
    <div className="counter">
      <h1>UseReducer Counter</h1>
      <div>
        <input
          type="text"
          placeholder="set counter value"
          onChange={inputHandler}
        />
        <h2 className="count-num">Count : {count}</h2>
        <div className="buttons-wrapper">
          <button
            onClick={() => {
              dispatch({ type: "increase" });
            }}
          >
            +
          </button>
          <button
            onClick={() => {
              dispatch({ type: "reset" });
            }}
          >
            reset
          </button>
          <button
            onClick={() => {
              dispatch({ type: "decrease" });
            }}
          >
            -
          </button>

        </div>
      </div>
    </div>
  );
};
export default ReducerCounter;

Enter fullscreen mode Exit fullscreen mode

Tip

Differences between useState and useReducer

useState is a basic Hook that manages simple state transformation while the useReducer is an additional Hook for managing more complex state logic.

Error Boundary

This captures and handles javascript errors anywhere in it's child tree. I implemented it following the documentation from React documentation.

404 Page

I created a 404 error page that cannot be found.

import React from 'react'

export default function NotFound() {
  return (
    <div className='notfound'>
      <h1>404</h1>
      <p>Error Page</p>
    </div>
  )
}

Enter fullscreen mode Exit fullscreen mode

SEO in React

I implemented SEO easily following what I was taught, some documentations 'https://ahrefs.com/blog/react-seo/', and youtube videos.

My work was easily hosted on a frontend hosting platform called 'vercel' and then pushed to github for proper documentation.

This custom hook might be easy but it is a good way of learning about hooks, state and useReducer mostly for beginners. It is easier understand.
I enjoyed working on this project and I know you would too.

Reach out for questions or any contributions.
Thanks to Altschool for the opportunity to learn and share my knowledge with others.

I hope this was helpful.

Top comments (1)

Collapse
 
abdulmaleekberry profile image
NAFIU ABDULMALIK

Hi Mary please I need help on this for more clarity