The goal of this example is to understand when states and effects happen when changing between different routes that use the same component.
Behavior is follows:
- visit: localhost:3001/1
- click
count++
. This makescount: 1
- click "2" to visit localhost:3001/2
- outcome: count is still 1
This is likely because in React the state kept in the virtual DOM structure, and identical structure implies identical state. So when we change from post 1 to 2, we still have a
Post
object, and state is unchanged.Next if we click:then the count is back to 0. This is because we changed the
- "Index" to go to localhost:3000
- "1" to go to localhost:3001/1
Post
object in the DOM to Index
and back, which resets everything.This example also illustrates how to prevent this from happening with
useEffect
.Bibliography: