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

146
Visualizações
Workaround Derived State in React

I have a component that renders a drop down box (HTML <select>). The data of that drop down box is a list of string supplied as one of the prop (let's call it data), and the index of the selected element is kept as a state (let's call it idx). There is also a button in this component that checks whether the option selected is valid or not.

Initially, everything works fine as the data is not empty. However, after a refactor on other parts, the data loading mechanism is now async. This means data supplied could be empty when this component is created. To handle this case, I initialize idx to undefined if the list is empty when this component is created.

Now there is a problem, when the component is created, idx is set to undefined. However, when the component get updated after the prop data is changed (to something not empty), idx is still undefined. This cause the checking mechanism to throw errors (when user click the button).

What is the best way to fix this issue?

Initially, I thought about derived state, since idx is clearly a state derived from data. However, there is an article on the react blog strongly discourage the use of derived states, and I am not sure whether my case fit into it or not.

So I took the recommended approach from that article. In the parent component, I compute a key prop, that is set to 0 when data is empty and 1 when it is not, every time when it renders this component. This solves the problem because the component will be rebuilt when key changes. However, I personally don't like this approach as it make the code of my parent component messier. It also resets all other states in the component (in my particular case, this is fine, but I can see problems if this component is more complex and has other states that I don't necessarily want to reset).

Are there other better ways to fix this problem?

about 4 years ago · Santiago Trujillo
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