Matt
Matt

Reputation: 1609

Run function only once in React

I have a function which creates an ID for a div with a random number appended to it for uniqueness. The problem is that I need to be able to run the random number generator only once on component load, otherwise the random number generation runs on every input.

const randomID = Math.floor(1000 + Math.random() * 9000);
const generateID = text => {
    return text.replace(/\s+/g, '-') + '-' + randomID;
};

I've considered using useEffect, but it doesn't seem to be running correct:

useEffect(() => {
    const randomID = Math.floor(1000 + Math.random() * 9000);
},[]);

How can I ensure the randomID number only runs once, guaranteeing the randomID number is only going to run when the component loads and not every time the component loads?

Upvotes: 0

Views: 1927

Answers (1)

Agustin Moles
Agustin Moles

Reputation: 1534

It's ok to use it inside the useEffect to make it run only once per component mount, but to use that value you should also have a state to set it and use it in your HTML element. Like this:

const [randomID, setRandomID] = useState(null);

useEffect(() => {
    setRandomID(Math.floor(1000 + Math.random() * 9000));
},[]);

Upvotes: 3

Related Questions