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

115
Visualizações
Weird React state behavior

I am working on a React project, and have run into an annoying bug. I have isolated the problem in the code below:

import ReactDOM from "react-dom";
import React, { useState } from "react";

const Variants = ({ variants, setVariants }) => {
  function toggleRemove(index) {
    setVariants((_variants) => {
      let newVariants = [..._variants];
      if (newVariants[index].action === "remove") {
        newVariants[index].action = undefined;
      } else {
        newVariants[index].action = "remove";
      }
      return newVariants;
    });
  }

  return (
    <>
      {variants.map((variant, index) => (
        <div>
          <span>{variant.title}</span>
          <button onClick={() => toggleRemove(index)}>Toggle remove</button>
        </div>
      ))}
    </>
  );
};

const AdminProductTools = ({ product }) => {
  const [variants, setVariants] = useState(product.variants);

  return (
    <div>
      <Variants variants={variants} setVariants={setVariants}></Variants>
      <p>{JSON.stringify(product)}</p>
    </div>
  );
};

const Product = () => {
  const [product, setProduct] = useState({
    variants: [{ title: "dummy1" }, { title: "dummy2" }],
  });

  return <AdminProductTools product={product} />;
};

const App = () => {
  return <Product />;
};

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);


When I hit the 'Toggle remove' button next to a variant, I only expect the 'variants' state to change. Somehow the 'product' prop in AdminProductTools is being updated too (as seen in cyan span), even though 'setProduct' is never called. Even weirder is, if you inspect Product in React DevTools, the 'product' state seems to update too, even though it is not reflected in the yellow span.

How can this be?

CodeSandbox: https://codesandbox.io/s/crazy-haze-wk92e?file=/src/index.js

about 4 years ago · Juan Pablo Isaza
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