Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

145
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!