How to Build a Countdown Timer in React with SOLID Principles
Alexandre Pereira
Software Engineer MERN | React.JS | Nodejs | Javascript | Typescript | MongoDB | GCP | Python
Building a countdown timer is a classic exercise in React. To make it even more interesting, we’ll use a SOLID approach to create reusable and testable components. This tutorial will guide you through implementing a 10-second countdown timer that stops at zero and changes the color of an element.
Applying SOLID Principles to Design
For a scalable and maintainable design, we’ll focus on the Single Responsibility Principle (SRP) and other SOLID principles as we build this timer.
Creating the Timer Logic with a Custom Hook
Let’s start with a custom hook, useCountdown, to handle the countdown logic. This isolates the timer’s logic, making it reusable.
Building the Countdown Component
Now, let’s create a CountdownDisplay component to show the countdown. This component follows SRP, focusing only on displaying the time.
Creating the Main Component
Next, we’ll create the main CountdownTimer component. This component will handle the color change when the countdown reaches zero.
领英推荐
Using Dependency Injection for Flexibility
Let’s improve flexibility by adding props that allow us to modify the countdown duration and color after the timer finishes. This follows the Dependency Inversion Principle, making the component more extensible.
Final App Component
Now, import and use the CountdownTimer component in your main App component.
Conclusion
In this tutorial, we built a countdown timer with React, keeping each component focused on a single responsibility. The use of a custom hook (useCountdown) allowed us to encapsulate the timer logic, making it reusable and easy to test. By applying SOLID principles, our countdown timer is now modular, extendable, and adaptable for future modifications.
Feel free to experiment by adding more features, such as pausing or resetting the timer. Applying SOLID principles helps keep the code clean and flexible for various scenarios. Happy coding!
Engenheiro de Dados | Engenheiro de Software | Python | Backend
3 个月I love articles with code examples. Thanks for sharing!
Senior Full Stack Software Engineer | Java | Spring Boot | React | AWS
3 个月Very good post
Data Engineer | Azure | Azure Databricks | Azure Data Factory | Azure Data Lake | Azure SQL | Databricks | PySpark | Apache Spark | Python
3 个月Great! I really liked the example and the use of clean architecture!
Senior Java Software Developer / Engineer | Java | Spring Boot | Backend focused
3 个月Applying SOLID principles in React ensures clean, modular code. Using a custom hook for timer logic makes components reusable and extendable.
Full Stack Engineer| Frontend Foused | React.js | Node.js | NextJS
3 个月I was thinking about this yesterday ??, thanks for sharing!