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

109
Visualizações
setting state with useState affects all useState hooks

I am trying to build an ecommerce website, and I hit a problem I cannot seem to resolve. I am very new to react and JS so have some patience please :)

I declared 4 useStates in my app.js:

const [elementeDinState, setElementeDinState] = useState([]);
const [currentCategorie, setCurrentCategorie] = useState("Acasa");
const [subCategorie, setSubcategorie] = useState([]);
const [cartContents, setCartContents] = useState([]);

const fetchData = useCallback(async () => {
    const data = await getCategories();
    setElementeDinState(data);
  }, []);
  useEffect(() => {
    fetchData().catch(console.error);
  }, [fetchData]);

const changeHeader = (dataFromMenuItem) => {
    setCurrentCategorie(dataFromMenuItem);
  };

const changeCopiiContent = (data1FromThere) => {
    setSubcategorie(data1FromThere);
  };

const changeCart = (dataFromCart) => {
    setCartContents(dataFromCart);
  };

I am passing the functions to change those states to different child components as props. my problem is, when I add items to cart it triggers a re render of my component (products listing component) that should not be affected by cartContents and that resets the state of said component to the initial value that changes the items being shown. does useState hook create a single global state comprised of all those states?

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

0

If these useState are defined in the app.js and then passed down, when a child will use them chasing the state will happen in the app.js so all the children of <App /> will be re-rendered.

I guess that your app.js looks similar:

function App() {
const [elementeDinState, setElementeDinState] = useState([]);
 // ...and the other hooks and methods

return (
   <cartContents setElementDinState={setElementeDinState} />
   <ProductList />
)
}

In this case the state is in the component so when <CartContents /> changes it, it will trigger a re-render of the and all its children <ProductList /> included.

To avoid this problem think better when each piece of state needs to be and put the state as near as possibile to that component. For example, if the state of the cart does not influence the Product list. Move the useState in the <Cart /> component.

about 4 years ago · Juan Pablo Isaza Relatório

0

well, seems like I wanted to change the way react works so I figured out a work around, based on what you guys told me. I declared the state of the productsComponent in the parent component and adding to cart now doesn't force a refresh of the items being shown. thank you!

about 4 years ago · Juan Pablo Isaza Relatório

0

From what I understand, your problem is that you're simply resetting the cartContents state every time you call the changeCart function, correct?

What you probably want, is to add (or remove ?) the item to the cart, like this?

const changeCart = (dataFromCart) => {
  setCartContents(oldContents => [...oldContents, dataFromCart]);
};
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