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

213
Visualizações
SetState not forcing a rerender on a functional component?

I have the following component, that doesn't rerender when the state is updated, even though the values of the state are used within the child components and the values are updated correctly.

import Paper from "@mui/material/Paper";
import React, {useState} from "react";
import Grid from "@mui/material/Grid";
import Knob from "./Knob";

export default function Knobs({knobSettings}) {
    const [values, setValues] = useState({0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0});
    console.log("render");
    const updateValue = (index, value) => {
        const localValues = values;
        localValues[index] = value;
        setValues(localValues);
        console.log(localValues, values)
    };

    const item = (index) => (
        <Grid item xs={1}>
            <Knob
                bipolar={knobSettings[index].bi}
                max={knobSettings[index].max}
                value={values[index]}
                onValueChange={(value) => updateValue(index, value)}
            />
        </Grid>
    );

    return (
        <Paper>
            <Grid container columns={3}>
                {item(0)}
                {item(1)}
                {item(2)}
                {item(3)}
                {item(4)}
                {item(5)}
            </Grid>
        </Paper>
    );
}

When handling the state within the knobs themselves, everything works nicely, but I need the state higher up and it seems to break here. Is that due to the way I generate items? I'd rather not have to copy the same code 6 times (as it's still all changing), so what'd be the best way to handle this?

(And is it possible to use an array in the state instead of an object with indexes? Updating arrays is always a bit tricky.)

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

0

Change this line

const localValues = values;

to this :

const localValues = [...values];

It is not updating because you are giving the same reference to setValues.

about 4 years ago · Juan Pablo Isaza Relatório

0

I'd rather not have to copy the same code 6 times

You can map over the items like so:

<Paper>
   <Grid container columns={3}>
      {values.map((item, index) => item(index))}
   </Grid>
</Paper>

Alternatively, if the length of values is not necessarily directly related to the amount of items, then this can be converted to a simple for loop, etc..

about 4 years ago · Juan Pablo Isaza Relatório

0

React does not do a deep comparison. So when you update the object key value react component will not get rerendered. You will not see the update on UI.

You can solve this like below.

const updateValue = (index, value) => {
  setValues((pre) => ({ ...pre, [index]: value }));
};
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