Last updated: Apr 6, 2024
Reading timeยท2 min
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.
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 sample uses the
Math.random()
function to generate a number in the range 1
(inclusive) to 5
(inclusive).
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.
console.log(Math.random()); // ๐๏ธ 0.9349907593750104 console.log(Math.random()); // ๐๏ธ 0.1028502928025743 console.log(Math.random()); // ๐๏ธ 0.9268013352071363
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.
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;
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.
I've also written an article on how to create a delay function in React.
You can learn more about the related topics by checking out the following tutorials: