create counter react

Create Counter React Tutorial

By Kevin Moore
AD

Have you ever found yourself in need of a counter in your React application, but struggled with the complexities of state management? React's built-in state management can be limiting, especially when dealing with counters that need to be shared across components. Enter the context API and useReducer, a powerful duo that simplifies state management and helps you create counters with ease. Let's dive in and learn how to create a counter in React using these tools.

Before we begin, ensure you have a good understanding of React's basic concepts, including components, props, and state. Familiarity with the useContext and useReducer hooks will also be beneficial. Let's start by setting up our project and installing the necessary dependencies.

Setting Up the Project

First, create a new React project using Create React App (CRA). Open your terminal, navigate to the desired project location, and run npx create-react-app counter-app. Once the project is set up, navigate into your new directory with cd counter-app.

AD
Counter App With React JS | React App For Beginners
Counter App With React JS | React App For Beginners
Building an Animated Counter with React and CSS
Building an Animated Counter with React and CSS
React projet setup
React projet setup

Since we'll be using the context API and useReducer, we don't need to install any additional dependencies. However, if you prefer to use TypeScript, you can install it via npx create-react-app counter-app --template typescript.

Creating the Counter Context

The context API allows us to pass data down the component tree without having to pass props through every level. Let's create our counter context and the provider component that will wrap our application.

React - 4. State and Like-Dislike Counter Component
React - 4. State and Like-Dislike Counter Component
React Hooks: useState(using the state hook) | HackerNoon
React Hooks: useState(using the state hook) | HackerNoon
React in 30 Seconds
React in 30 Seconds

Create a new file named CounterContext.js in the src folder, and add the following code:

```javascript // src/CounterContext.js import React, { createContext, useReducer } from 'react'; const initialState = { count: 0, }; const CounterContext = createContext(); const counterReducer = (state, action) => { switch (action.type) { case 'INCREMENT': return { count: state.count + 1 }; case 'DECREMENT': return { count: state.count - 1 }; case 'RESET': return { count: 0 }; default: return state; } }; const CounterProvider = ({ children }) => { const [state, dispatch] = useReducer(counterReducer, initialState); return ( {children} ); }; export { CounterProvider, CounterContext }; ```

Explanation of CounterContext.js

In this file, we create a context using createContext and a reducer function counterReducer to handle our counter's state transitions. We also create a provider component CounterProvider that returns the context provider with the current state and dispatch function.

AD

Now, let's wrap our application with the CounterProvider component.

React | Day 1
React | Day 1
React Context State
React Context State
How to Create a React.js Project from Scratch?
How to Create a React.js Project from Scratch?
react server components are connected to each other with the same symbol in front of them
react server components are connected to each other with the same symbol in front of them
Build Your First React App (2 Hours)
Build Your First React App (2 Hours)
Create New React App
Create New React App

Wrapping the App with CounterProvider

Open the src/index.js file and wrap the App component with the CounterProvider like this:

```javascript // src/index.js import React from 'react'; import ReactDOM from 'react-dom'; import { CounterProvider } from './CounterContext'; import App from './App'; ReactDOM.render( , document.getElementById('root') ); ```

Creating the Counters

Now that we have our context set up, let's create two functional components, IncrementCounter and DecrementCounter, that will use the context to update the counter's state.

AD

Create two new files named IncrementCounter.js and DecrementCounter.js in the src folder, and add the following code to each respective file:

How to Create an Editable Table Component in React
How to Create an Editable Table Component in React
React Fundamental
React Fundamental
The Ultimate React Hooks Cheat Sheet: 7 Hooks in One Visual Guide
The Ultimate React Hooks Cheat Sheet: 7 Hooks in One Visual Guide
Create a React Project From Scratch – Part I
Create a React Project From Scratch – Part I
React
React
10 REACT PROJECTS EVERY FRONTEND DEVELOPER SHOULD BUILD
10 REACT PROJECTS EVERY FRONTEND DEVELOPER SHOULD BUILD
Heineken Interactive Counter Concept
Heineken Interactive Counter Concept
How to Set Up a React App With Vite
How to Set Up a React App With Vite
Empowering Web Development with React: Strategies for Modern Web Applications - Root-Nation.com
Empowering Web Development with React: Strategies for Modern Web Applications - Root-Nation.com
Are You Weak in Creating Context API? Then You Have to Read This Article
Are You Weak in Creating Context API? Then You Have to Read This Article
a board game with the words react on it and an image of a maze in front of
a board game with the words react on it and an image of a maze in front of
the react logo on a computer screen
the react logo on a computer screen
two blue and black logos, one with an atomic symbol on it's side
two blue and black logos, one with an atomic symbol on it's side
20 REACT HOOKS EVERY DEVELOPER SHOULD KNOW
20 REACT HOOKS EVERY DEVELOPER SHOULD KNOW
```javascript // src/IncrementCounter.js import React, { useContext } from 'react'; import { CounterContext } from './CounterContext'; const IncrementCounter = () => { const { dispatch } = useContext(CounterContext); return ( ); }; export default IncrementCounter; ```

The IncrementCounter component retrieves the dispatch function from the context and dispatches the 'INCREMENT' action when the button is clicked.

The DecrementCounter Component

The DecrementCounter component is similar to the IncrementCounter component, but it dispatches the 'DECREMENT' action instead. You can find the implementation in the src/DecrementCounter.js file.

AD

Displaying the Counter Value

Let's create a component that displays the current counter value and a reset button. Create a new file named CounterDisplay.js in the src folder, and add the following code:

```javascript // src/CounterDisplay.js import React, { useContext } from 'react'; import { CounterContext } from './CounterContext'; const CounterDisplay = () => { const { count, dispatch } = useContext(CounterContext); return (
Counter: {count}
); }; export default CounterDisplay; ```

The CounterDisplay component displays the current counter value and resets the counter when the "Reset" button is clicked.

Using the Components in Our App

Finally, let's use the components we created in our application. Open the src/App.js file and replace the default code with the following:

```javascript // src/App.js import React from 'react'; import './App.css'; import IncrementCounter from './IncrementCounter'; import DecrementCounter from './DecrementCounter'; import CounterDisplay from './CounterDisplay'; const App = () => { return (

Welcome to the Counter App!

); }; export default App; ```

And that's it! Your counter application is now ready. When you run npm start in your terminal, you should see a simple React app with a counter that can be incremented, decremented, and reset.

Keep practicing and exploring the useReducer and context API hooks to create more complex state management systems in your React applications. Happy coding!

AD