![]() |
VOOZH | about |
JavaScript setInterval() repeatedly executes a function with a fixed time delay. It can be challenging to use the setInterval method in React. For instance, if we wish to update the delay parameter, we might have to deal with a lot of life cycle methods. To avoid this hassle, we can use a custom useInterval hook.
The useInterval hook implements the setInterval method in a declarative manner. By combining the setInterval and clearInterval methods, the useInterval hook sets up an interval and then clears it upon unmounting. We can simply declare an interval with a delay. The arguments for the useInterval hooks can be dynamic. This enables us to have a dynamically adjusted delay without having to worry about the start or end of an interval.
In terms of usage, useInterval resembles setInterval quite a bit:
Syntax:
useInterval(() => {
// func
}, delay);
React useInterval Hook accepts a function and a delay where,
Note: The arguments are dynamic, unlike those in the setInterval method.
Let's look at an example of how to use the useInterval custom hook in React:
Approach: We will create a counter with a dynamically adjustable delay using the useInterval custom hook.
Implementation and Setup for Creating React Application:
Step 1: Make a project directory, head over to the terminal, and create a react app named counter using the following command:
npx create-react-app counterAfter the counter app is created, switch to the new folder counter by typing the command below:
cd counter Step 2: Modify Your project structure. Add a useInterval.js file in the src folder. We will modify the folder and keep the files we need for this example. Now, make sure your file structure looks like this:
Step 3: Include the following code in your index.html file, located in the public folder of your project directory.
File name: index.html
Step 4: Creating the useInterval custom hook. In the useInterval.js file, we will write a function to create a custom useInterval hook which we can use in our counter application.
File name: useInterval.js
Step 5: Creating the counter component.
File name: App.js
Step 6: Add the following code to App.css to style the counter application.
File name: App.css
Step 7: Add the following code in the index.js file. The index.js file serves as the main entry point, and inside it, the App.js file is rendered at the root ID of the DOM.
File name: index.js
Step to run the application: Run our application by using the following command:
npm start Output: By default, the React project will run on port 3000. You can access it at localhost:3000 on your browser. You can start the counter by entering the delay time in milliseconds and clicking on the play button.