Day 44 of the React Js challenge: Implementing an auto increment counter in React Js

Posted by

React Js Challenge Day 44 | Auto Increment Counter in React Js

React Js Challenge Day 44 | Auto Increment Counter in React Js

Welcome to day 44 of the React Js challenge! Today, we will be implementing an auto increment counter in React Js.

Creating the Counter Component

First, we need to create a new file for our counter component. Let’s call it Counter.js. In this file, we will define a simple React component that will display a counter and increment it automatically.

    
import React, { useState, useEffect } from 'react';

const Counter = () => {
  const [count, setCount] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => {
      setCount(prevCount => prevCount + 1);
    }, 1000);

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

  return (
    

Auto Increment Counter:

{count}

); }; export default Counter;

Using the Counter Component

Now that we have our Counter component, let’s use it in our main app file, App.js. We can simply import the Counter component and render it in the App component.

    
import React from 'react';
import Counter from './Counter';

const App = () => {
  return (
    

Auto Increment Counter in React Js

); }; export default App;

Final Thoughts

And there you have it! We have successfully implemented an auto increment counter in React Js. The counter will start at 0 and increment by 1 every second. This is just a simple example, but you can easily modify it to suit your needs.

Happy coding!

0 0 votes
Article Rating
2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@debugdriver
8 months ago

Thanks for watching!!
Don't forget to like share and subscribe 👍

@ajiteshmishra0005
8 months ago

Hii

I have to appear in Javascript interviews.

So from where can I practice Javascript programs which are generally asked in Interview in codeing part