Tari Ibaba is a software developer with years of experience building websites and apps. He has written extensively on a wide range of programming topics and has created dozens of apps and open-source libraries.
The useEffect hook is called in a component after the first render and every time the component updates. By the timer useEffect is called, the real DOM would have been updated to reflect any state changes in the component.
Let’s take a look at a quick example to practically observe this behavior:
The first time the component renders from page loading, useEffect is called and uses the document.title property to set the page title to a string whose value depends on a count state variable.
The page title is changed from useEffect being called after the component is rendered.
If you watch closely, you’ll see that the page title was initially “Coding Beauty React Tutorial”, before the component was added to the DOM and the page title was changed from the useEffect call.
useEffect will also be called when the state is changed:
The page title is changed from useEffect being called after the component is updated.
As you might know, useEffect accepts an optional dependency array as its second argument. This array contains the state variables, props, and functions that it should watch for changes.
In our example, the dependency array contains only the count state variable, so useEffect will only be called when the count state changes.
useEffect called twice in React 18?
React 18 introduced a new development-only check to Strict Mode. This new check automatically unmounts and remounts a component when it mounts for the first time, and restores the previous state on the second mount.
Note: The check was added because of a new feature that will be added to React in the future. Learn more about it here.
This means that the first render causes useEffect to actually be called two times, instead of just once.
Here’s an example that lets us observe this new behavior.
It’s a basic time-counting app that implements the core logic that can be used to build timer and stopwatch apps.
We create an interval listener with setInterval() that increments a time state by 1 every second. The listener is in a useEffect that has an empty dependency array ([]), because we want it to be registered only when the component mounts.
But watch what happens when we check out the result on the web page:
The seconds go up by 2 every second.
The seconds are going up by 2 every second instead of 1! Because React 18’s new check causes the component to be mounted twice, an useEffect is called accordingly.
We can fix this issue by unregistering the interval listener in the useEffect‘s cleanup function.
The cleanup function that the useEffect callback returns is called when the component is mounted. So when React 18 does the compulsory first unmounting, the first interval listener is unregistered with clearInterval(). When the second interval listener is registered on the second mount, it will be the only active listener, ensuring that the time state is incremented by the correct value of 1 every second.
The seconds go up by 1 every second – success.
Note that even if we didn’t have this issue of useEffect being called twice, we would still have to unregister the listener in the cleanup function, to prevent memory leaks after the component is removed from the DOM.
The “unexpected reserved word (await)” error occurs in JavaScript when you use the await keyword in a function that is not specified as async. To fix it, add an async modifier to the function to mark it as async.
The “Unexpected reserved word ‘await'” error occurring in JavaScript.
Here’s an example of the error occurring:
index.jsCopied!
function getName() {
// ❌ SyntaxError: Unexpected reserved word
const str = await Promise.resolve('Coding Beauty');
return str;
}
Note: As this is a syntax error, the function doesn’t need to be invoked for it to be detected, and no part of the code runs until it is resolved.
The async and await keywords work together in JavaScript (hence the commonly used term, async/await); to use the await keyword in a function, you must add the async modifier to the function to specify that it is an async function.
JavaScriptCopied!
// ✅ Use "async" keyword modifier
async function getName() {
// ✅ Successful assignment - no error
const str = await Promise.resolve('Coding Beauty');
return str;
}
Fix “Unexpected reserved word (await)” error in nested function
If you’re using the await keyword, it’s likely that you already know that it has to be in an async function. What probably happened is that you nested functions and mistakenly ommited the async modifier from the innermost function containing the await keyword.
For await to work, the deepest function in the nesting hierarchy is required to be specified as async. It won’t work even if any or all of the outer functions are marked as async.
So we resolve the error in this case by adding the async modifier to the innermost function:
In this example, we should be able to remove the async keyword from the outer function, as it isn’t performing any asynchronous operations with await, but this depends on whether the caller of createTask() is expecting it to return a Promise or not.
Here’s another example where this mistake frequently happens; using await in an array looping method:
JavaScriptCopied!
// ❌ SyntaxError: Unexpected reserved word
async function processPhotos(photoIds) {
const data = await Promise.all(photoIds.map((photoId) => {
const res = await fetch(`http://example.com/photos/${photoId}`);
return await res.json();
}));
// process data...
}
Like in the previous example, the error occurs because the async keyword modifier is absent from the map() callback, even though it’s present in the function that calls map(). The fix is the same, add async to the map() callback.
JavaScriptCopied!
// ✅ No error
async function processPhotos(photoIds) {
const data = await Promise.all(
photoIds.map(async (photoId) => {
const res = await fetch(`http://example.com/photos/${photoId}`);
return await res.json();
})
);
// processing...
}
Use await at top level
If you’re trying to use await at the top level of your file, you’ll need to set the type attribute to "module" in the script tag referencing the file in the HTML. This works when your code runs in browser environments.
For example:
index.htmlCopied!
<script type="module" src="index.js"></script>
Now you’ll be able to use await at the global scope in your file, e.g.:
To handle the onScroll event on a Vue element, assign a function to the scroll event of the element and use the event object the function receives to perform an action. The action will occur whenever the user scrolls up or down on the page.
The function (event handler) passed to the scroll event is invoked whenever the viewport is scrolled. It is called with an event object, which you can use to perform actions and access information related to the scroll event.
The currentTarget property of this event object returns the element that the scroll listener was attached to.
We use the element’s scrollTop property to get how far the element’s scrollbar is from its topmost position. Then we update the state variable with the new value, and this reflects on the page.
Handle onScroll event on window object
We can also handle the onScroll event on the global window object, to perform an action when the viewport is scrolled.
type: a string representing the event type to listen for, e.g., 'click', 'keydown', 'scroll', etc.
listener: the function called when the event fires.
It also has some optional parameters, which you can learn more about here.
We call addEventListener() in the mounted hook to register the listener once the component renders as the page loads. mounted is only called for a component when it has been added to the DOM, so the listener will not be registered multiple times.
We also called the removeEventListener() method to unregister the event listener and prevent a memory leak. We place the call in the beforeUnmount hook so that it happens just before the component is removed from the DOM.
We create the boolean state with the useState hook. useState returns an array of two values, the first is the value of the state, the second is a function that updates the state when it is called.
We pass a callback function to setVisible because the callback is always passed the latest visible state.
Tip: Always pass a function to setState when the new state is computed from the current state data.
In our case, the callback simply negates the boolean value and returns the result to negate the state.
The logical NOT (!) operator converts a truthy value to false and a falsy value to true.
Note: In JavaScript there are only 6 falsy values: undefined, null, '' (empty string), NaN, 0, and false. Every other value is truthy and will result in false when negated.
Perform action on boolean state toggle
Sometimes you want to perform an action outside of re-rendering when the boolean state changes in the component, e.g., a network request. To carry out such an action, place the code in the useEffect hook and include the boolean state variable in useEffect‘s dependencies array.
The code in the useEffect hook runs after the component mounts or updates from a change in the visible state. Here, the state controls the visibility of an element, so in the hook, we check if the element is visible, and if so, we make a network request to a server to update view stats associated with the element.
Perform action on boolean state change but skip first render
Depending on your scenario, you might want the action to run when the component updates from a state change, but not it when it first mounts.
We can do this by creating a ref flag variable having an initial value of false in the first render, and change its value to true for all subsequent renders.
useRef returns a mutable ref object that doesn’t change value when a component is updated. Also, modifying the value of this object’s current property does not cause a re-render. This is in contrast to the setState update function returned from useState.
If the ref’s value is false, we prevent the action from happening in useEffect and change the value to true for the following renders. Otherwise, we execute the action.
In React apps, event listeners or observers perform certain actions when specific events occur. While it’s quite easy to create event listeners in React, there are common pitfalls you need to avoid to prevent confusing errors. These mistakes are made most often by beginners, but it’s not rare for them to be the reason for one of your debugging sessions as a reasonably experienced developer.
In this article, we’ll be exploring some of these common mistakes, and what you should do instead.
1. Accessing state variables without dealing with updates
Take a look at this simple React app. It’s essentially a basic stopwatch app, counting up indefinitely from zero.
However, when we run this app, the results are not what we’d expect:
Stuck at 1
This happens because the time state variable being referred to by the setInterval() callback/closure refers to the stale state that was fresh at the time when the closure was defined.
The closure is only able to access the time variable in the first render (which had a value of 0) but can’t access the new time value in subsequent renders. JavaScript closure remembers the variables from the place where it was defined.
The issue is also due to the fact that the setInterval() closure is defined only once in the component.
The time variable from the first render will always have a value of 0, as React doesn’t mutate a state variable directly when setState is called, but instead creates a new variable containing the new state. So when the setInterval closure is called, it only ever updates the state to 1.
Here are some ways to avoid this mistake and prevent unexpected problems.
1. Pass function to setState
One way to avoid this error is by passing a callback to the state updater function (setState) instead of passing a value directly. React will ensure that the callback always receives the most recent state, avoiding the need to access state variables that might contain old state. It will set the state to the value the callback returns.
The time is increased by 1 every second – success.
Now the time state will be incremented by 1 every time the setInterval() callback runs, just like it’s supposed to.
2. Event listener re-registration
Another solution is to re-register the event listener with a new callback every time the state is changed, so the callback always accesses the fresh state from the enclosing scope.
We do this by passing the state variable to useEffect‘s dependencies array:
Every time the time state is changed, a new callback accessing the fresh state is registered with setInterval(). setTime() is called with the latest time state added to 1, which increments the state value.
2. Registering event handler multiple times
This is a mistake frequently made by developers new to React hooks and functional components. Without a basic understanding of the re-rendering process in React, you might try to register event listeners like this:
If you do have a basic understanding of this, you should be able to already guess what this will lead to on the web page.
The seconds keep accelerating.It eventually gets as bad as this.
What’s happening?
What’s happening is that in a functional component, code outside hooks, and outside the returned JSX markup is executed every time the component re-renders.
Here’s a basic breakdown of what happens in a timeline:
1st render: listener 1 registered
1 second after listener 1 registration: time state updated, causing another re-render)
2nd render: listener 2 registered.
Listener 1 never got de-registered after the re-render, so…
1 second after last listener 1 call: state updated
3rd render: listener 3 registered.
Listener 2 never got de-registered after the re-render, so…
1 second after listener 2 registration: state updated
4th render: listener 4 registered.
1 second after last listener 1 call: state updated
5th render: listener 5 registered.
1 second after last listener 2 call: state updated
6th render: listener 6 registered.
Listener 3 never got de-registered after the re-render, so…
1 second after listener3 registration: state updated.
7th render: listener 7 registered…
Eventually, things spiral out of control as hundreds and then thousands (and then millions) of callbacks are created, each running at different times within the span of a second, incrementing the time by 1.
The fix for this is already in the first example in this article – put the event listener in the useEffect hook, and make sure to pass an empty dependencies array ([]) as the second argument.
useEffect runs after the first render and whenever any of the values in its dependencies array change, so passing an empty array makes it run only on the first render.
The time increases steadily, but by 2.
The time increases steadily now, but as you can see in the demo, it goes up by 2 seconds, instead of 1 second in our very first example. This is because in React 18 strict mode, all components mount, unmount, then mount again. so useEffect runs twice even with an empty dependencies array, creating two listeners that update the time by 1 every second.
We can fix this issue by turning off strict mode, but we’ll see a much better way to do so in the next section.
3. Not unregistering event handler on component unmount.
What happened here was a memory leak. We should have ensured that any created event listener is unregistered when the component unmounts. So when React 18 strict mode does the compulsory unmounting of the component, the first interval listener is unregistered before the second listener is registered when the component mounts again. Only the second listener will be left and the time will be updated correctly every second – by 1.
You can perform an action when the component unmounts by placing in the function useEffect optionally returns. So we use clearInterval to unregister the interval listener there.
useEffect‘s cleanup function runs after every re-render, not only when the component unmounts. This prevents memory leaks that happen when an observable prop changes value without the observers in the component unsubscribing from the previous observable value.
Conclusion
Creating event listeners in React is pretty straightforward, you just need to be aware of these caveats, so you avoid unexpected errors and frustrating debugging spells. Avoid accessing stale state variables, don’t register more event listeners than required, and always unregister the event listener when the component unmounts.
We create a reusable toSeconds() function to easily convert the hours and minutes to seconds.
The function is quite easy to understand; 1 hour equals 3600 seconds, so we multiply the hour value by 3600 to get the seconds equivalent. Similarly, 1 minute equals 60 seconds, so we multiply the minute value by 60 to get the seconds equivalent.
After this, we add the equivalent seconds values to the seconds argument to get the total seconds.
We could rewrite the function to accept the time values as named properties of an object, instead of as multiple parameters.
This approach makes it easier to understand the role of each value passed to the function, a
Convert HH:mm:ss to seconds in JavaScript
Sometimes the time input to convert to seconds is a string in a time format, like HH:mm:ss. To convert to seconds in this case, we’ll separate the individual time values by the separator (: in this case), cast them each to numbers, and perform the same time conversion steps done in our previous examples.
The input string here is in the HH:mm:ss format; the hour, minute, and second values are separated by a colon (:) and are each represented by a minimum of 2 digits.
The Stringsplit() method splits a string into an array of substrings separated by a given separator in the original string. We pass a colon as the separator to get an array of the individual time values.
After getting this array, we use the map() method to transform each time value into a number. The map() method takes a callback and calls it on each element of an array and uses the result to populate a new array. For our scenario, the callback is simply the Number() constructor, so each time value in the array is converted to a number.
The second one is longer, but it makes it clear exactly what arguments are passed to the map() callback. In the first one, map() automatically passes 3 arguments to its callback, which could be problematic if the callback returns a different result depending on the number of arguments it receives, for instance, a parseInt() callback.
We then use a destructuring assignment to unpack the number array values into separate hour, minute, and second variables.
After doing this, we perform the same multiplication and addition we did in the first example, to convert the hours and minutes to seconds and get the total seconds.
1. Only keep first object in array with property value
To filter duplicate objects from an array by a property in JavaScript, use the filter() method to filter out elements that are not the first in the array having the property value.
The Arrayfilter() tests each element in an array against a condition specified by a callback function, and creates a new array filled with elements that pass the test. It doesn’t modify the original array.
The ArrayfindIndex() method searches through elements in an array and returns the index of the first one that passes a test, specified by the callback function passed to it. We use it to find the first array element with the same property value as the object filter() is currently testing.
In our example, the filter() condition for the object is that its array index be the same as the result of findIndex(). If this condition is true, it will mean that the object is the first array element with the property value. If it’s false, it’ll mean that there’s already an array item with that property value, so the object is a duplicate and shouldn’t be included in the result.
JavaScriptCopied!
const arr = [
{
name: 'John',
location: 'Los Angeles',
},
{
name: 'Kate',
location: 'New York',
},
{
name: 'Mike',
location: 'New York',
},
];
// true - first object with location of New York
console.log(1 === arr.findIndex((obj) => obj.location === 'New York'));
// false - will not be included in result
console.log(2 === arr.findIndex((obj) => obj.location === 'New York'));
Filter duplicate objects from array by multiple properties
Depending on your scenario, you may want an object to be considered a duplicate only if it has two or more properties that have the same value – multiple property values that are the same.
For that case, we’ll use filter() and findIndex() as before, but we’ll add extra comparisons between filter()‘s object and findIndex()‘s object for all the properties.
We use the for...of loop to iterate over the array and perform an action for each object.
For each object, we use the find() method to check if it already exists in the unique array. Arrayfind() searches for the first object in an array that passes a specified test, similar to findIndex(), but it returns the object itself instead of its array index.
If it’s not in the unique array, we simply add it with the push() method.
This method is not a one-liner like the first one, but you may find it easier to understand. It seems like the natural way you would go about removing duplicate items from a list as a human.
Filter duplicate objects from array by multiple properties
Like in the previous method, if multiple properties are used to determine if an object is a duplicate, you can simply add more checks for the properties – this time in the find() method:
Create a boolean state variable to store the value of the checkbox.
Set an onChange event listener on the input checkbox.
In the listener, use the event object’s target.checked property to check if the checkbox is checked.
Store the checked value in a state variable to be able to check whether the checkbox is checked from outside the event listener.
App.jsCopied!
import { useState } from 'react';
export default function App() {
const [agreement, setAgreement] = useState(false);
const handleChange = (event) => {
setAgreement(event.target.checked);
}
return (
<div>
<div id="app">
<input
type="checkbox"
name="agreement"
onChange={handleChange}
/>
<label for="agreement">
I agree to the terms and conditions
</label>
<br /><br />
<button disabled={!agreement}>Continue</button>
</div>
</div>
);
}
The button is disabled depending on the checkbox’s checked value.
The event object’s target property represents the checkbox input element; the value of its checked property indicates whether the checkbox is checked or not.
The event object is passed to the onChange listener, which will be invoked whenever the checkbox is checked or unchecked.
We use the useState React hook to store the checkbox’s checked state. useState returns an array of two values; the first is a variable that stores the state, and the second is a function that updates the state when it is called.
So every time the checkbox is checked or unchecked, the agreement state variable will be automatically toggled to true or false.
We set the button’s disabled prop to the negation of agreement to disable and enable it when agreement is true and false respectively.
Check if checkbox is checked with ref
Instead of controlling the checkbox’s checked value with React state, we can create an uncontrolled checkbox and check whether it is checked with a ref.
A message depending on the checkbox’s checked value is displayed.
The data in a controlled input is handled by React state, but for uncontrolled inputs, it is handled by the DOM itself. This is why the input checkbox in the example above doesn’t have a value prop or onChange event handler set. Instead, we check if the checkbox is checked with a React ref. The DOM updates the checked value when the user toggles the checkbox.
We create a ref object with the useRef hook and assign it to the ref prop of the checkbox input. Doing this sets the current property of the ref object to the DOM object that represents the checkbox.
useRef returns a mutable object that maintains its value when a component updates. Also, modifying the value of this object’s current property doesn’t cause a re-render. This is unlike the setState update function return from the useState hooks.
Although the React documentation recommends using controlled components, uncontrolled components offer some advantages. You might prefer them if the form is very simple and doesn’t need instant validation, and values only need to be accessed when the form is submitted.
To round a number to 2 decimal places in JavaScript, call the toFixed() method on the number, i.e., num.toFixed(2). toFixed() will round and format the number to 2 decimal places.
The toFixed() method takes a number F and returns a string representation of a number with F number of digits after the decimal points. F here is determined by the first argument passed to toFixed(), the fractionDigits argument.
Sometimes the input might be stored as a string. In this case, we’ll first need to convert the number to a float with the parseFloat() function before using toFixed() to round it to 2 decimal places.
For example:
JavaScriptCopied!
const numStr = '17.23593';
// 👇 convert string to float with parseFloat()
const num = parseFloat(numStr);
const result = num.toFixed(2); // 17.24
console.log(result);
Not all decimal numbers can be represented precisely in binary, so there are some rounding errors in JavaScript’s floating-point number system. For example:
Like in the first one, here 1.015 is rounded down to 2 decimal places as 1.01 instead of 1.02, because 1.015 also can’t be represented accurately in the binary number system.
One of the most popular examples of this flaw is the classic 0.1 + 0.2:
We iterate over the elements in the list object with the forEach() method. This forEach() method works similarly to ArrayforEach().
classList.remove() method
We use the classList.remove() method to remove a class from the elements. You can remove multiple classes by passing more arguments to remove().
JavaScriptCopied!
const elements = document.querySelectorAll('*');
elements.forEach((element) => {
element.classList.remove('big', 'bold');
});
If any of the classes passed to remove() doesn’t exist on the element, remove() will ignore it, instead of throwing an error.
Remove class from all children elements of element
The previous example works for removing a class from every single element in the DOM. What if you want to remove all elements that are children of a specific DOM element, for instance, just children of the .container element in our example?
To do this, just prefix the * with the element’s selector and separate them with a space. I mean:
JavaScriptCopied!
// Remove class from all children elements of .container div
const elements = document.querySelectorAll('.container *');
elements.forEach((element) => {
element.classList.remove('big');
});
Add class to all elements
Just like the classList.remove() method removes one or more classes from an element, the classList.add() method adds one or more classes to an element. This means that we can use it in the forEach() method to remove a class from all DOM elements: