setTimeout in React
Overview
In React, we often deal with timeouts while building various applications. A setTimeout method enables us to invoke a function after a particular interval. However, using the traditional setTimeout in React can be challenging because of its various caveats. It is necessary to track the timeouts inside the useEffect hook and clear them for efficient working of the application.
What is setTimeout?
setTimeout is a javascript method that executes a piece of code only once after a specified period.
Syntax:
- func:
It is the function that invokes after a specified time. - delay:
It specifies how long the timer should wait before executing the specified code or function in milliseconds. - The setTimeout in react returns a timeoutId, passed to the clearTimeout method.
- The timeoutId identifies a particular timer created by the setTimeout function.
Example:
Using setTimeout in React Components
We can use the setTimeout in React components just like in JavaScript. However, there are certain caveats that we should take into consideration.
We will need the useEffect hook to use setTimeout in React components. It might not be a good idea to set a timeout directly within a component because React will regenerate the setTimeout method each time the component is re-rendered, creating a new timeout. These timeouts will soon bloat our application, causing it to function poorly. Additionally, numerous states change, resulting in extra re-renders.
Therefore, we will use the useEffect hook to create a timeout for React components. The useEffect hook performs side effects when the component re-renders. It accepts a callback to perform the side effects and a dependency array. The dependencies are state variables that trigger these side effects when altered. To control the timeouts, we will place them inside the useEffect hook.
Example:
To create a timeout once the component mounts, we will use the useEffect hook with an empty dependency array.
In this example, we have used the setTimeout function inside the useEffect hook to display the content after 5 seconds.
Output:
Let us understand how we can create timeouts on re-renders.
Clearing setTimeout
We shall use the useEffect hook with a non-empty dependency array if we wish to create a timeout on re-renders each time the component’s state changes. However, this will generate new timeouts as we execute the side effects when the state changes, thus bloating the application.
To resolve this issue, we must clear the previous timeout before creating a new one. We use the clearTimeout method to perform some cleanup before rerunning the side effect. The clearTimeout method cancels the timeouts generated by the setTimeout method.
In React, when a component unmounts, it is removed from the DOM, and any resources it was using, such as timers, should also be cleaned up to prevent memory leaks. If a timeout is set in a component, and that component is unmounted before the timeout completes, it will execute its callback function even though the component is no longer in the DOM. It can cause problems such as updating the state or triggering side effects on a component that no longer exists, leading to bugs and memory leaks. To avoid this, we can clear the previous timeout before creating a new one using the clearTimeout method.
Syntax:
The setTimeout method returns a timeoutId that uniquely identifies a particular timeout.
Example:
Explanation:
We will use the useEffect hook and return a function in the callback that will execute when the component unmounts. This function will clear the previously generated timeout.
In this example, as the count variable changes, a new timeout is generated, and "Hello, I'm a timeout" is console logged after 2 seconds. We will clear the previous timeouts by writing a cleanup function.
Output:
setTimeout in Class Components
This example shows how to use the setTimeout in react class component.
Example:
Explanation:
- Using the componentDidMount for the initial render.
- Using componentWillUnmount() in class-based React components for returning a function is similar to using useEffect hooks in functional components.
Output:
Using State in setTimeout
In a setTimeout, a state property does not use its current value. Let us consider the following example:
Example:
In this example, we have an input field where we will type in a text to display as an alert after three seconds.
Output:
The setTimeout will use the value it was initially called with if we change the input value right after clicking the button.
We need to use the useRef hook to retrieve the most recent value.
- Using the useRef hook, we will create a reference and use the useEffect hook to track changes to the text variable.
- We'll use this reference instead of the text variable in the timeout to get the most recent text value.
Output:
After typing "hello" and clicking on " send alert", we immediately manipulated the text value to "hello mam," which gets displayed as an alert after 2 seconds instead of just "hello".
React useTimeout Custom Hook
We have figured out how to deal with the timeouts in React. We keep track of the timeouts and clear them up in React. But it can be a hassle to remember to clean it up when the component unmounts, etc. Therefore, we can use a custom setTimeout hook instead.
- The useTimeout hook receives a callback function and a delay.
- We will create references to keep track of the active timeout and callback using the useRef hook.
- Using the useEffect hook, we will track the change in state and handle the cleanup after the timeout.
- Then, we will clear previous timeouts and assign the new timeout.
Usage:
Please include the above code in a separate file, import it, and use the custom useTimeout hook in React components.
Example:
Output:
Fuel Your Full-Stack Passion! Our Full Stack Web Development Course Blends JavaScript Brilliance with Back-End Craftsmanship. Ready to Dive In? Enroll Now!
Conclusion
- setTimeout is a javascript method that executes a piece of code only once after a specified period.
- Using the traditional setTimeout in React can be challenging because of its various caveats.
- We will need the useEffect hook to use the setTimeout method in React components. To create a timeout once the component mounts, we will use the useEffect hook with an empty dependency array.
- React will regenerate the setTimeout each time the component re-renders, creating a new timeout. These timeouts will soon bloat our application, causing it to function poorly. To resolve this issue, we must clear the previous timeout before creating a new one.
- Our callback may still execute if we don't clear our timeouts when a component unmounts, leading to memory leaks in our application.
- In a setTimeout, a state property does not use its current value and will use the value it was initially called. Therefore, we will use the useRef hook to retrieve the most recent value.
- We can avoid the hassle of tracking and clearing timeouts by using the custom useTimeout hook.