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

194
Visualizações
Set state inside a component in ReactJs

I have this component in my react js application:

import React, { useState } from "react";
import Select, { components, DropdownIndicatorProps } from "react-select";
import { ColourOption, colourOptions } from "./docs/data";

const Component = () => {
  const [state, setState] = useState();
  console.log(state);
  const DropdownIndicator = (props) => {
    const { menuIsOpen } = props.selectProps;
    setState(menuIsOpen);
    return (
      <components.DropdownIndicator {...props}>12</components.DropdownIndicator>
    );
  };

  return (
    <Select
      closeMenuOnSelect={false}
      components={{ DropdownIndicator }}
      defaultValue={[colourOptions[4], colourOptions[5]]}
      isMulti
      options={colourOptions}
    />
  );
};

export default Component;

In the DropDownIndicator component i set the state:

const {
  menuIsOpen
} = props.selectProps;
setState(menuIsOpen);

Setting the state in that place i get the next warning: Warning: Cannot update a component (Component) while rendering a different component (DropdownIndicator). To locate the bad setState() call inside DropdownIndicator .
Question: How can i fix this warning and to make it disappear?
demo: https://codesandbox.io/s/codesandboxer-example-forked-97sx0?file=/example.tsx:0-724

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

0

You should call setState inside useEffect

const DropdownIndicator = (props) => {
    const { menuIsOpen } = props.selectProps;

    useEffect(() => {
        setState(menuIsOpen);
      });

    return (
      <components.DropdownIndicator {...props}>12</components.DropdownIndicator>
    );
  };

What does useEffect do? By using this Hook, you tell React that your component needs to do something after render. Read more about useEffect

Incase if your setState is depend of menuIsOpen. Pass to useEffect as dependency.

 const DropdownIndicator = (props) => {
    const { menuIsOpen } = props.selectProps;

      useEffect(() => {
        setState(menuIsOpen);
      },[menuIsOpen]);

    return (
      <components.DropdownIndicator {...props}>12</components.DropdownIndicator>
    );
  };

Complete solution on CodeSandbox

about 4 years ago · Juan Pablo Isaza Relatório

0

Just mark the useState with default value as false

const [state, setState] = useState(false);

looks like when you are doing setState(menuIsOpen); for the first time, its value is undefined and DropdownIndicator is not yet finished with first rendering,

[Hypothesis] There must be some code with React.Component as per the stack trace, based on undefined/null check. But when given initialState, the error is not occurring.

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