This project demonstrates two approaches to building a simple counter application in React, created with Vite and TypeScript:
- Main Branch: Using the
useStatehook for state management. - useReducer Branch: Using the
useReducerhook for state management.
This project showcases how to implement a simple counter application using two different React hooks for state management. The counter allows users to increment, decrement, and reset the count value.
The project is built using Vite, a fast build tool that offers an optimized development experience, and TypeScript, which provides type safety in JavaScript applications.
-
Main Branch (useState): This branch uses the
useStatehook to manage the counter's state. It's straightforward and ideal for simpler state management needs. -
useReducer Branch: This branch uses the
useReducerhook, which is more suitable for complex state management scenarios. The reducer logic is placed in a separate file to demonstrate better code organization.
- Node.js (v14 or later)
- npm or Yarn
-
Clone the repository:
git clone https://github.com/CamiloPinzon/State-Management.git cd State-Management -
Install dependencies:
npm install
or
yarn install
To run the project on the main branch (useState):
npm run devor
yarn devThis will start the Vite development server. By default, the project will be available at http://localhost:5173. You can view the project by navigating to this URL in your web browser.
To switch to the useReducer branch:
git checkout useReducerThen, start the development server again:
npm run devor
yarn devreact-counter-example/
├── src/
│ ├── components/
│ │ └── Counter.tsx
│ ├── reducers/ (only in useReducer branch)
│ │ └── counterReducer.ts
│ ├── App.tsx
│ ├── main.tsx
│ └── index.css
├── .gitignore
├── index.html
├── package.json
├── tsconfig.json
└── vite.config.ts
-
Main Branch (useState):
- The
Countercomponent handles all state management withuseState.
- The
-
useReducer Branch:
- The
Countercomponent utilizesuseReducerfor state management. - The reducer logic is moved to a separate file (
counterReducer.ts) under thereducersdirectory.
- The
- Increment: Increases the count by 1.
- Decrement: Decreases the count by 1.
- Reset: Resets the count to 0.
const increment = () => setCount(prevCount => prevCount + 1);const increment = () => dispatch({ type: 'increment' });To learn more about the technologies used in this project, check out the following resources:
This project is licensed under the MIT License.