React Increment Decrement Counter

ReactReactBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL react(("`React`")) -.-> react/FundamentalsGroup(["`Fundamentals`"]) react(("`React`")) -.-> react/AdvancedConceptsGroup(["`Advanced Concepts`"]) react(("`React`")) -.-> react/StateManagementGroup(["`State Management`"]) react/FundamentalsGroup -.-> react/jsx("`JSX`") react/FundamentalsGroup -.-> react/components_props("`Components and Props`") react/FundamentalsGroup -.-> react/event_handling("`Handling Events`") react/AdvancedConceptsGroup -.-> react/hooks("`React Hooks`") react/StateManagementGroup -.-> react/use_state_reducer("`Using useState and useReducer`") subgraph Lab Skills react/jsx -.-> lab-67585{{"`React Increment Decrement Counter`"}} react/components_props -.-> lab-67585{{"`React Increment Decrement Counter`"}} react/event_handling -.-> lab-67585{{"`React Increment Decrement Counter`"}} react/hooks -.-> lab-67585{{"`React Increment Decrement Counter`"}} react/use_state_reducer -.-> lab-67585{{"`React Increment Decrement Counter`"}} end

Counter Game

To get started, open the editor. You can see the following files from your editor.

├── public
├── src
│   ├── components
│   │  └── HomePage
│   │       ├── HomePage.css
│   │       └── HomePage.js
│   ├── App.js
│   ├── index.css
│   └── index.js
├── package-lock.json
└── package.json

Requirements

  • To install the project dependencies, use the following command:

    npm i
  • Please complete this challenge in the components/HomePage/HomePage.js file.

  • Use the useState hook to define two state variables: count and timer.

  • Use the useEffect hook to start the timer when the timer state variable changes.

  • Check the timer value. If it is zero, the effect returns early and doesn't do anything.

  • If the timer value is not zero, it sets up an interval that decrements the timer value by 1 every second (1000 milliseconds).

  • Return a cleanup function that clears the interval when the component is unmounted or when the timer value changes.

Example

Once you have completed the code, run it with the following command:

npm start

The finished result is as follows:

finished

Summary

Congratulations! You have completed the Counter Game. You can practice more challenge in LabEx to improve your skills.

Other React Tutorials you may like