Smart Systems for Home

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

How to Generate a Random Number in React JS

· 5 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

Generating a random number in React JS is straightforward: use JavaScript's built-in Math.random() inside your component, then scale and round it to the range you need. The most common pattern is Math.floor(Math.random() * (max - min + 1)) + min for an inclusive integer between min and max. React does not have a special random-number API — it is just JavaScript — but where and when you call it matters for rendering behavior. This guide walks through a working example, the pitfalls that trip people up, and how to keep the value stable across re-renders.

What You'll Need

  • A working React project (Create React App, Vite, Next.js, or any setup that renders components).
  • Node.js and npm installed if you are starting from scratch.
  • A basic understanding of JSX and React state (useState) or hooks (useEffect).
  • No extra libraries — Math.random() is built into JavaScript.

Step-by-Step

  1. Create a component file. In your src folder, add a file such as RandomNumber.jsx. Import React and the hooks you need: import { useState } from 'react';. If your project uses the automatic JSX runtime (most modern setups), you do not need to import React itself.
  2. Write a helper function for the range. At the top of the file, define a function that returns an integer between two inclusive bounds:
    function getRandomInt(min, max) {
      return Math.floor(Math.random() * (max - min + 1)) + min;
    }
    The + 1 is what makes max inclusive. Without it, the highest value you can get is max - 1.
  3. Set up state to hold the number. Inside your component, call . Passing a function to useState (lazy initializer) means the random value is computed only once on the first render, not on every render.
  4. Render the number. Return JSX that displays it: <p>Your number: {number}</p>. Because the value lives in state, React will re-render the component when it changes.
  5. Add a button to regenerate. Include a button with an onClick handler that calls setNumber(getRandomInt(1, 100)). Clicking it produces a new number and updates the display.
  6. Import and use the component. In App.jsx (or your entry component), add import RandomNumber from './RandomNumber'; and render <RandomNumber /> inside the return statement.
  7. Run the app. Start your dev server (for Vite, npm run dev; for Create React App, npm start). Open the local URL shown in the terminal, and you should see a number between 1 and 100 with a button to generate a new one.
  8. Generate on mount only (optional). If you need a random value once when the component appears — for example, a random ID or a shuffled item — use useEffect(() => { setNumber(getRandomInt(1, 100)); }, []);. The empty dependency array ensures it runs once after the first render.
  9. Verify the range. Log a few hundred results to the console to confirm the minimum and maximum appear. A quick loop like for (let i = 0; i < 1000; i++) console.log(getRandomInt(1, 6)); should show 1 and 6 occasionally, proving both ends are reachable.

Common Mistakes

  • Calling Math.random() directly in JSX. Writing <p>{Math.random()}</p> generates a new number on every render, so the value flickers whenever any state changes. Store it in state or a ref instead.
  • Forgetting the + 1. Math.floor(Math.random() * max) + min with an off-by-one formula excludes the upper bound. Always test the extremes.
  • Using Math.round instead of Math.floor. Rounding skews the distribution — the lowest and highest values get half the probability of the middle ones. Math.floor keeps it uniform.
  • Re-seeding on every render. If you call the generator inside the component body without state or a lazy initializer, React's re-renders will keep producing new numbers unexpectedly.
  • Expecting cryptographic security. Math.random() is not suitable for passwords, tokens, or security-sensitive values. Use crypto.getRandomValues() or a dedicated library for those cases.

Tips

  • Keep the generator in a separate utility file if you use it in multiple components — it makes testing and reuse easier.
  • For a random decimal between 0 and 1, Math.random() alone is enough. For a decimal in a range, use Math.random() * (max - min) + min without rounding.
  • To pick a random item from an array, combine the integer helper with the array length: arr[getRandomInt(0, arr.length - 1)].
  • If you need the same random value on server and client (for example in Next.js), generate it in useEffect or pass it as a prop to avoid hydration mismatches.
  • Use the lazy initializer form of useState whenever the initial value is expensive or should not change between renders.

Troubleshooting

  • The number changes every time I type in an input. The generator is being called during render. Move it into state with a lazy initializer or into useEffect.
  • The number never reaches the maximum. Check your formula — you likely omitted the + 1 or used the wrong operator precedence.
  • I get the same number repeatedly. Math.random() is pseudorandom but should vary. If it does not, confirm you are not caching the result in a module-level constant outside the component.
  • Hydration error in Next.js or Remix. Server-rendered HTML and client-rendered HTML disagree because the random value differs. Generate the number only on the client inside useEffect, or render a placeholder until mounted.
  • The button does nothing. Ensure the handler calls setNumber with a new value and that you are not mutating state directly. Check the console for errors.

Frequently Asked Questions

Can I generate a random number without state?

Yes, if you only need it once — for example, a constant defined outside the component or inside a useRef. But if the value should update on user action, state is the right tool because it triggers re-renders.

How do I get a random number between 1 and 10 in React?

Use Math.floor(Math.random() * 10) + 1. That yields integers from 1 through 10 inclusive.

Is Math.random() secure enough for passwords?

No. It is not cryptographically secure. For tokens or passwords, use the Web Crypto API's crypto.getRandomValues() or a vetted library.

Why does my random number change on every render?

Because you are calling the generator in the component body or in JSX. React re-runs the function on each render, producing a new value. Store it in state or a ref to keep it stable.

Can I generate a random number on the server in Next.js?

You can, but the client will produce a different value on hydration, causing a mismatch warning. Generate it client-side in useEffect or pass a server-generated value as a prop if consistency is required.

How do I pick a random element from an array?

Use arr[Math.floor(Math.random() * arr.length)]. This works for any array and returns one element with uniform probability.