cod;nncode. learn. thrive.

Increment decrement counter using React hooks

Posted Dec 24, 2022

Welcome to the #react10 Day 1 challenge.

In this challenge you will be developing a counter game aka increment decrement counter using React hooks i.e with useState and useEffect in which you can click a button to increase the count value. This you can play with your friends and challenge them to click click click... as much as possible in a given time.

Demo

Get Github Code

Pre-requisites

  • Code Editor (like VS Code)
  • React basic knowledge (as in this challenge we are not focusing on explaining about the react concepts)
  • Basic knowledge of HTML

Lets Begin!

Create a folder structure like this,

-codin
--react10 (this folder we'll use to put all our challenges day wise)
---day1 (open this directory in the vs code)
Final Path: ~codin\react10\day1\

Open terminal in the vs code and run these commands,

> npx create-react-app counter-game
> cd counter-game
> npm start

After doing all of this, your UI would be like,

increment decrement counter in React hooks

Code Cleanup

Delete following files from the file explorer,
counter-game\src\App.css
counter-game\src\App.test.js
counter-game\src\logo.svg
counter-game\src\reportWebVitals.js
counter-game\src\setupTests.js

Remove below lines form index.js

import reportWebVitals from "./reportWebVitals";
reportWebVitals();

Go to App.js and remove these line

import logo from "./logo.svg";
import "./App.css";

and remove all the JSX code and JSX,

return <div className="App">CustomForm</div>;

Current App.js

function App() {
  return <div className="App">Counter</div>;
}

export default App;

index.js

import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

Folder Structure

increment decrement counter in React hooks

UI

increment decrement counter in React hooks

Run these commands in a new terminal (let the other terminal run our project),

> cd counter-game (run this command if you are in 'react10\day1>' path)
> mkdir src\components\HomePage
> type NUL > src\components\HomePage\HomePage.js
> type NUL > src\components\HomePage\HomePage.css

Don't get confused with the above commands, you can also create files or folders using file explorer manually. But if you remember these commands this will help you to increase your productivity and also make you look 'cool' while screen sharing :)

Go to HomePage.js and write,

import React from "react";

function HomePage() {
  return <div>Counter</div>;
}

export default HomePage;

Import HomePage.js in App.js like this,

import HomePage from "./components/HomePage/HomePage";

function App() {
  return (
    <div className="App">
      <HomePage />
    </div>
  );
}

export default App;

Your UI should not have any changes after doing the above steps. Lets add our main logic for increment decrement counter in React hooks.

Now add this counter logic in the HomePage.js,

//states -
//creating these states to track count value and countdown
const [count, setCount] = useState(0);
const [timer, setTimer] = useState(0);

//useEffect -
//using this hook to run our timer
useEffect(() => {
  if (timer === 0) return;

  const interval = setInterval(() => {
    setTimer(timer - 1);
  }, 1000);

  return () => {
    clearInterval(interval);
  };
}, [timer]);

After adding required JSX our final HomePage.js should look like -

import React, { useEffect, useState } from "react";
import "./HomePage.css";

function HomePage() {
  const [count, setCount] = useState(0);
  const [timer, setTimer] = useState(0);
  useEffect(() => {
    if (timer === 0) return;

    const interval = setInterval(() => {
      setTimer(timer - 1);
    }, 1000);

    return () => {
      clearInterval(interval);
    };
  }, [timer]);

  return (
    <div className="home-container">
      <div className="home-timer">timer:{timer}</div>
      <div className="home-count">{count}</div>
      <button
        className="home-btn-start btn"
        onClick={() => {
          setTimer(10);
          setCount(0);
        }}
        disabled={timer !== 0}
      >
        start
      </button>
      <button
        className="home-btn-click btn"
        onClick={() => setCount(count + 1)}
        disabled={timer === 0}
      >
        click me
      </button>
      <button
        className="home-btn-reset btn"
        onClick={() => {
          setCount(0);
          setTimer(0);
        }}
      >
        reset
      </button>
    </div>
  );
}

export default HomePage;

Styling in HomePage.css

.home-container {
  display: flex;
  justify-content: space-evenly;
  align-items: center;
  flex-direction: column;
  font-family: monospace;
  background-color: black;
  color: white;
  height: 100%;
}

.home-header {
  font-size: 2rem;
}

.home-count {
  font-size: 10rem;
  margin: 30px;
  text-shadow: 10px 5px red;
}

.home-timer {
  font-size: 5rem;
  opacity: 0.5;
  text-shadow: 5px 5px #424242;
}

.home-btn-start {
  background-color: #e7da3d;
}

.home-btn-click {
  background-color: #3dd1e7;
}

.home-btn-reset {
  background-color: #e73d9f;
}

.btn {
  font-family: inherit;
  font-size: 1.5rem;
  border-radius: 10px;
  color: black;
  width: 50%;
  max-width: 200px;
  height: 50px;
  border: none;
  font-weight: 600;
}

.btn:active {
  background-color: white;
  border: black 1px solid;
}

Final Result

increment decrement counter in React hooks

Bonus: To run your localhost project on your Mobile devices -

  1. Open cmd and run command
    > ipconfig
    
  2. Copy IPv4 Address(looks like - 192.168..*)
  3. Connect you mobile device with the same WiFi/Internet networt
  4. Open URL - 192.168..*:3000 (Note : 3000 is your port number in which your project is running)
  5. Enjoy your Game :)
  6. Come back tomorrow for the #day2 challenge. Good day!
Your feedback is our favorite notification! Share your thoughts about this page and make us smile.