Nyi Nyi Hmue Aung
Nyi Nyi Hmue Aung

Reputation: 736

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 :

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

Upvotes: 2

Views: 2184

Answers (2)

Dane
Dane

Reputation: 9582

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

Upvotes: 4

Christian Orth
Christian Orth

Reputation: 4673

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/

Upvotes: 1

Related Questions