How to generate a random number in React

avatar
Borislav Hadzhiev

Last updated: Apr 6, 2024
2 min

banner

# Generate a random number in React

Use the Math.random() function to generate a random number in React.

The Math.random function returns a number in the range from 0 to less than 1 but can also be used to generate a number in a specific range.

App.js
import {useState} from 'react'; const App = () => { const [num, setNum] = useState(0); function randomNumberInRange(min, max) { // ๐Ÿ‘‡๏ธ Get the number between min (inclusive) and max (inclusive) return Math.floor(Math.random() * (max - min + 1)) + min; } const handleClick = () => { setNum(randomNumberInRange(1, 5)); }; return ( <div> <h2>number is: {num}</h2> <button onClick={handleClick}>Generate random number</button> </div> ); }; export default App;
The code for this article is available on GitHub

The code sample uses the Math.random() function to generate a number in the range 1 (inclusive) to 5 (inclusive).

generate random number

If you don't need to generate a number in a specified range, but simply need a random number, use the Math.random() function directly.

App.js
console.log(Math.random()); // ๐Ÿ‘‰๏ธ 0.9349907593750104 console.log(Math.random()); // ๐Ÿ‘‰๏ธ 0.1028502928025743 console.log(Math.random()); // ๐Ÿ‘‰๏ธ 0.9268013352071363

# Generate a random number every N seconds

If you need to generate a random number every N seconds and render it in your component, use the useEffect hook to set up the interval.

App.js
import {useEffect, useState} from 'react'; const App = () => { const [num, setNum] = useState(0); function randomNumberInRange(min, max) { // ๐Ÿ‘‡๏ธ Get the number between min (inclusive) and max (inclusive) return Math.floor(Math.random() * (max - min + 1)) + min; } useEffect(() => { const interval = setInterval(() => { // ๐Ÿ‘‡๏ธ Generate a random number between 1 and 10 setNum(randomNumberInRange(1, 10)); }, 1000); // ๐Ÿ‘ˆ๏ธ runs every 1 second return () => { clearInterval(interval); }; }, []); return ( <div> <h2>number is: {num}</h2> </div> ); }; export default App;

generate random number every n seconds

The code for this article is available on GitHub

The example uses the setInterval() method to invoke a function every 1 second.

The second argument we passed to the setInterval() method is the delay (in milliseconds) between invocations of the function.

If you don't pass an argument for the delay, it defaults to 0.

In the function, we generate a random number between 1 and 10 and update the state variable.

The function we returned from the useEffect hook is run when the component unmounts.

We used the clearInterval() method to cancel the repeating action that we set up using setInterval.

This is something you should always do when using methods like setInterval() or addEventListener(), because if you don't clean up when the component gets unmounted, you would get a memory leak in your application.

The code for this article is available on GitHub

I've also written an article on how to create a delay function in React.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev