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.
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:
- Go in Edit Mode by selecting a note for .5s
- Select 2/3 elements by clicking on them
- 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)
2
Answers
If you use React.memo you can cache the Child components and prevent their re-renders.
You have to wrap the functions you pass as props inside
useCallback
, otherwise they will be different on every Parent render, invalidating the memoization.You can see a working example here.
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 wheneditMode
goes fromtrue
tofalse
, it will set the item’sselected
state.Add this to your
<Child />
component: