Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Component loses state on re-render

I need some help with React. As far as I know, it should be working just fine. But, it is not working. What I am trying to do is :

  • I have a list of todo.
  • You can add new todo and you can also expand the todo section.
  • When you expand the todo section, it will open up full screen.

The problem is, newly added todos are not showing up when you expand the todo. Why is that? I am basically using the same component. Why is it that the newly added todos dissapeared when todo section is expanded? And vice-versa, when you expand, add new todo and close the modal, newly added todos are not showing up. How can I make new todo persists regardless of the todo section is expanded or not.

Please, take a look at the small demo app I built.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

full codesandbox link

>Solution :

The Todo component is not getting re-rendered, but unmounted and remounted. You have your state inside the Todo component, but each time expand changes, Todo gets unmounted and remounted inside the Dialog component. This causes it to lose its internal state. The solution would be to lift the state up in the tree, i.e., to keep the state inside Demo component.

Relevant section in docs: Lifting State Up

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading