Common Mistaks during Events Call in Reactjs
These common mistaks you must avoid when trigger events in Reactjs

When particular events take place in React apps, event listeners or observers do specific actions. Even though creating event listeners in React is rather simple, there are several frequent mistakes you should watch out for. These errors are most frequently made by beginners, but even if you are a decently skilled developer, they could still lead to a debugging session.
In this article, we’ll look at a few of these typical errors and suggest some alternatives.
1. Using state variables without having to deal with updates
Check out this straightforward React app. It functions essentially as a stopwatch software that counts up continuously from zero.
JavaScript
import { useState, useEffect } from 'react';
export default function App() {
const [time, setTime] = useState(0);
useEffect(() => {
const timer = setInterval(() => {
setTime(time + 1);
}, 1000);
return () => {
window.clearInterval(timer);
}
}, []);
return (
<div>
Seconds: {time}
</div>
);
}
However, when we run this app, the results are not what we’d expect:
This occurs as a result of the time state variable being referenced to by the setInterval() callback/closure referencing the fresh state at the moment the closure was defined rather than the stale state.
The time variable can only be accessed by the closure once, while it had a value of 0, and it cannot access the updated time value in subsequent renders. The variables from the place where they were defined are remembered by JavaScript closure.
The setInterval() closure is only declared once in the component, which is another contributing factor to the problem.
Since React doesn’t directly alter a state variable when setState is called, it instead generates a new variable holding the state, the time variable from the first render will always have a value of 0.
2. Pass function to setState
Passing a callback rather than a value straight to the state updater function (setState) is one technique to prevent this problem. In order to prevent having to access state variables that can contain outdated state, React will make sure that the callback always gets the most recent state. The value that the callback returns will be used to set the state.
For our example, we will apply this as follows:
JavaScript
import { useState, useEffect } from 'react';
export default function App() {
const [time, setTime] = useState(0);
useEffect(() => {
const timer = setInterval(() => {
// 👇 Pass callback
setTime((prevTime) => prevTime + 1);
}, 1000);
return () => {
window.clearInterval(timer);
}
}, []);
return (
<div>
Seconds: {time}
</div>
);
}
Now, every time the setInterval() callback executes, the time state will be increased by 1 as intended.
3. Event listener re-registration
Another option is to continually register a new callback with the event listener so that it always has access to the most recent state from the enclosing scope.
To accomplish this, we give the state variable to the dependencies array of useEffect:
JavaScript
import { useState } from 'react';
export default function App() {
const [time, setTime] = useState(0);
setInterval(() => {
setTime((prevTime) => prevTime + 1);
}, 1000);
return (
<div>
Seconds: {time}
</div>
);
}
Or you might put it in a useEffect
hook like this:
JavaScript
import { useState } from 'react';
export default function App() {
const [time, setTime] = useState(0);
useEffect(() => {
setInterval(() => {
setTime((prevTime) => prevTime + 1);
}, 1000);
});
return (
<div>
Seconds: {time}
</div>
);
}
If you do grasp this fundamentally, you should be able to predict where this will lead on the web page.
What is going on?
What happens is that every time a functional component re-renders, code outside hooks and outside the output JSX markup is performed.
Are you ready to embark on a journey that will transform you into a ReactJS maestro? Look no further! Our ReactJS Programming Book is your ultimate companion for mastering this powerful JavaScript library. 🚀
📚 Why Choose Our ReactJS Programming Book?
🧠 Comprehensive Learning: Dive deep into ReactJS with a structured, step-by-step approach that takes you from novice to pro.
👩💻 Hands-On Practice: Learn by doing! With real-world projects and exercises, you’ll gain practical experience that sets you apart.
📈 Stay Updated: React evolves fast, and so do we! Our book keeps you up-to-date with the latest best practices and features.
🎯 Solve Real Problems: Tackle common React challenges head-on with expert tips and solutions.
📖 In-Depth Content: We cover React fundamentals, advanced concepts, and state-of-the-art techniques, ensuring you’re well-rounded.
👥 Community Support: Join our thriving online community of React enthusiasts for networking, advice, and collaboration.
🏆 Achieve Your Goals: Whether you aim to land a high-paying job, build your dream app, or stay ahead of the curve, our book is your ticket to success.
🌐 Global Appeal: ReactJS is used worldwide. Our book is suitable for developers of all backgrounds and skill levels.#reactjs #frontend #nextjs
#javascript
Don’t miss out on this opportunity to become a ReactJS expert! Grab your copy now and unlock the doors to endless possibilities. 🌟
🎁 Bonus: Get exclusive access to valuable resources, code samples, and updates when you purchase our ReactJS Programming Book!