![]() |
VOOZH | about |
We often run into timeouts when building applications in React. setTimeout() executes code after a specified period only once. Usually, we don't need to worry about clearing out our timeouts when using setTimeout. However, it can be challenging to use the setTimeout method in React because we might wish to manipulate data after a certain amount of time.
Even though the component might have been removed by then, the timeout is still attempting to start. This might even cause memory leaks. To resolve this, we must keep track of the timeouts we create in our code and clean them. This will function, but it can be a hassle to remember to clean it up when you unmount, etc. Therefore, we will use a custom setTimeout hook.
The useTimeout hook implements the setTimeout method in a declarative manner. This follows similar principles to that of the custom useInterval hook.
In terms of usage, useTimeout resembles the setTimeout method quite a bit:
Syntax:
useTimeout(() => {
// func
}, delay);
useTimeout Hook accepts a function and a delay where,
Let's look at an example of how to use the useTimeout custom hook in React:
Approach: We will display a message after a specified time using the custom useTimeout hook.
Start by following the steps below:
Step 1: Make a project directory, head over to the terminal, and create a react app named message using the following command:
npx create-react-app message
After the message app is created, switch to the new folder message by typing the command below:
cd message
Step 2: Modify Your project structure. Add a useTimeout.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.
Step 4: Creating the useTimeout custom hook.
In the useTimeout.js file, we will write a function to create a custom useTimeout hook which we can use in our message application.
useTimeout.js:
Step 5: Creating the message component.
App.js:
Step 6: Add the following code to App.css to style the message application.
App.css:
Step 7: Add the following code in 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.
Step to run the application: Run the 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.
In five seconds, the message will appear.