DEV Community

Discussion on: Don't duplicate your data - Learnings from code reviews

Collapse
 
lester016 profile image
Lester016 • Edited

When the posts props change that would cause the PostList component to re render so when that components re render all the code inside that component would execute again thus filtering the updated value of props posts. Why it would still filter the old value of props posts? I don't get it.

Collapse
 
jkettmann profile image
Johannes Kettmann

You're right about the re-rendering part. But state is only initialised when the component mounts.

So during the very first render the selectedDay state is initialized to null and the filteredPosts state is initialized to posts.

Next let's assume that the user selects a day. Then both states are set according to the user selection.

If the parent triggers a re-render of the PostList component for any reason both states variables stay the same. They are not initialized again. That's why the filteredPosts state still contains an old version.

If the component would unmount completely than you would be right. In that case all the code is executed again and the state is initialized to the values I mentioned above.

I hope I could clarify the problem. If you have further questions don't hesitate to ask :)