Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

668
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda