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

React – Resetting children state when parent changes its state in functional components

I’m working with a list of notes in React Native, and I was using a bad-performant method to select/deselect the notes when I’m "edit mode". Everytime I selected a note, the application had to re-render the entire list everytime. If I do a test with 100 notes, I get input lags when I select/deselect a note, obviously.

So I decided to move the "select state" to the single Child component. By doing this, I’m having the re-render only on that component, so it’s a huge improvement of performance. Until here, everything’s normal.

The problem is when I’m disabling edit mode. If I select, for example, 3 notes, and I disable the "edit mode", those notes will remain selected (indeed also the style will persist). I’d like to reset the state of all the selected note, or finding a valid alternative.

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

I recreated the scene using React (not React Native) on CodeSandbox with a Parent and a Child: https://codesandbox.io/s/loving-field-bh0k9k

The behavior is exactly the same. I hope you can help me out. Thanks.

tl;dr:

Use-case:

  1. Go in Edit Mode by selecting a note for .5s
  2. Select 2/3 elements by clicking on them
  3. Disable Edit Mode by selecting a note for .5s

Expectation: all elements get deselected (state of children resetted)

Reality: elements don’t get deselected (state of children remains the same)

>Solution :

this is easy enough to do with a useEffect hook.
It allows you to "watch" variable changes over time.

When editMode changes the contents of the Effect hook runs, so when editMode goes from true to false, it will set the item’s selected state.

Add this to your <Child /> component:

  useEffect(() => {
    if (!editMode) {
      setSelected(false);
    }
  }, [editMode]);
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