Home > Software engineering >  Component loses state on re-render
Component loses state on re-render

Time:08-16

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.

full codesandbox link

CodePudding user response:

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

CodePudding user response:

You're state gets lost in case it is not managed globally or a layer above. To solve that you could take a look at Redux. It's a library for managing and centralizing application state. It is open-source, well adopted, a good library to know and can also be used for further javascript frameworks like Angular.

https://react-redux.js.org/

  • Related