Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Generate a Random Number in React: Quick How-To

· 4 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

You generate a random number in React the same way you do in plain JavaScript: call Math.random(). React does not ship its own random-number function. The one React-specific rule is where you call it: put the call inside a useState initializer or an event handler, never directly in the component body, or the number will change on every re-render. The shortest working version is const [n, setN] = useState(() => Math.floor(Math.random() * 100) + 1); for a whole number from 1 to 100.

What You'll Need

  • A React project that already runs (Create React App, Vite, Next.js, or similar).
  • Node.js and npm installed if you are starting a project from scratch.
  • A code editor and a browser for testing.
  • Basic familiarity with JSX and React hooks such as useState.

Step-by-Step

  1. Create or open a component. If you need a new project, run npm create vite@latest my-app -- --template react, then cd my-app and npm install. Open src/App.jsx (or App.js in older setups).
  2. Import useState. Add import { useState } from 'react'; at the top of the file.
  3. Decide your range. Math.random() returns a decimal from 0 up to but not including 1. To get a whole number from 1 to 100, multiply by 100, round down with Math.floor, then add 1. To get 0 to 99, drop the + 1.
  4. Create the state with a lazy initializer. Write . The arrow function passed to useState runs only on the first render, so the number stays stable until you change it.
  5. Add a button that regenerates the number. In the JSX, add <button => setNumber(Math.floor(Math.random() * 100) + 1)}>New number</button>. Event handlers are the correct place for a fresh random value.
  6. Display the value. Render it with <p>Your number: {number}</p>.
  7. Save and test. Run npm run dev (Vite) or npm start (Create React App), open the local URL, and click the button several times. The number should change only when you click.
  8. Optional: extract a helper. For reuse, add a small function such as function randomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } and call randomInt(1, 100) in both places.

Common Mistakes

  • Calling Math.random() in the component body. Every render produces a new value, so the number flickers or changes when unrelated state updates. Use a lazy useState initializer or an event handler instead.
  • Forgetting Math.floor. Without it you get a long decimal like 42.7183, not a whole number.
  • Off-by-one ranges. Math.floor(Math.random() * 10) gives 0–9, not 1–10. Add 1 for a 1-based range.
  • Expecting unique numbers. Math.random() can repeat values; it does not track what it already returned.
  • Using random values for keys or IDs in lists. A new random key on each render forces React to remount elements. Use stable IDs instead.
  • Assuming it is secure. Math.random() is fine for games and UI, but not for passwords, tokens, or anything security-related.

Tips

  • Keep the range in a constant like const MAX = 100; so the initializer and the button handler stay in sync.
  • For a dice roll, use randomInt(1, 6); for a coin flip, Math.random() < 0.5 ? 'Heads' : 'Tails'.
  • If you need a cryptographically strong value in the browser, use crypto.getRandomValues() instead of Math.random().
  • When generating on the server (for example in Next.js), remember the server and client can produce different values; generate on one side or in an effect to avoid hydration mismatches.

Troubleshooting

  • The number changes on every keystroke or state update. The random call is in the render path. Move it into a useState initializer or an event handler.
  • The button does nothing. Check that you passed the function to onClick (not called it immediately) and that setNumber is the setter from the same useState call.
  • You get the same number repeatedly. With a small range, repeats are normal. If you need no repeats, keep a Set of used values and regenerate until you get a new one.
  • You see a hydration warning in Next.js or similar. The server-rendered value differs from the client one. Generate the number inside useEffect after mount, or render a placeholder until the client is ready.
  • Nothing renders at all. Check the browser console for errors, confirm the component is imported and mounted, and restart the dev server.

Frequently Asked Questions

Does React have a built-in random number function?

No. You use JavaScript's Math.random() (or crypto.getRandomValues() for stronger randomness) and store the result in React state.

How do I get a random whole number between two values?

Use Math.floor(Math.random() * (max - min + 1)) + min. For example, min = 1 and max = 100 gives 1 through 100 inclusive.

Why does my random number change when I type in an input?

Because the random call sits in the component body and runs on every render. Move it into a lazy useState initializer so it runs once.

Can I use Math.random() for passwords or tokens?

No. It is not cryptographically secure. Use crypto.getRandomValues() in the browser or the crypto module in Node.js for security-sensitive values.

How do I generate a random number only once when the component loads?

Pass a function to useState: useState(() => Math.random()). React calls it only on the first render.

Can I get a random number without repeats?

Yes, but you have to track used values yourself, for example with a Set in state, and regenerate until you get an unused number. Math.random() alone does not prevent repeats.