Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

670
Visualizações
How to prevent useState from rerendering the component again?

RadioButton changing their positions

import { nanoid } from 'nanoid';
import React from 'react';

export default function Question(props) {
  const answers = [...props.incorrect_answers, props.correct_answer];

  const [selectedAnswer, setSelectedAnswer] = React.useState();

  function handleChange(event) {
    setSelectedAnswer(event.target.value);
    console.log(event.target.value);
  }
  // Randomize answer of the Question
  function createRandom(arr) {
    let myArr = [...arr];
    let randomizedArr = [];

    while (myArr.length > 0) {
      let randomIndex = Math.floor(Math.random() * myArr.length);
      randomizedArr.push(myArr[randomIndex]);
      myArr.splice(randomIndex, 1);
    }
    return randomizedArr;
  }
  const randomizedArr = createRandom(answers);

  // RadioButton for the answers
  const RadioButton = ({ label, value, onChange }) => {
    return (
      <label>
        <input
          type="radio"
          name="answers"
          value={value}
          checked={selectedAnswer === value}
          onChange={onChange}
        />
        {label}
      </label>
    );
  };

  const answersElements = randomizedArr.map((answer) => {
    return (
      <RadioButton
        key={nanoid()}
        label={answer}
        value={answer}
        onChange={handleChange}
      />
    );
  });

  return (
    <div className="question-row">
      <div className="single-question">{props.question}</div>
      <div className="answers">{answersElements}</div>
    </div>
  );
}

RadioButton changing their positions

When I select a radiobutton answer , React rerender the RaidoButton component and call my Randomize function which randomize the answers. I do not know how to prevent Randomize function from being called after the first time. in the two pictures when I select an answer for the first question , the answers get randomized again , I want to prevent this behavior

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

This is an XY question .

You need the component to be re-rendered when the state changes (if only to update which radio button is checked).

The problem is that you need the randomization function to run only on initial load.


Create a state for the random array:

 const [randomizedArr, setRandomizedArr] = useState([]);

Then populate it in an effects hook with an empty dependency array (so it only runs on initial load of the component).

 useEffect(() => { const randomizedArr = createRandom(answers); setRandomizedArr(randomizedArr); }, []);
about 4 years ago · Juan Pablo Isaza Relatório

0

const [randomizedArr, setRandomizedArr] = React.useState([]);
  const [selectedAnswer, setSelectedAnswer] = React.useState();

  React.useEffect(() => {
    const answers = [...props.incorrect_answers, props.correct_answer];
    const randomizedArr = createRandom(answers);
    setRandomizedArr(randomizedArr);
  }, [props.incorrect_answers, props.correct_answer]);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda