i recreated the problem in this CodeSandbox
https://codesandbox.io/s/competent-newton-up21l?file=/pages/index.js
i have two routes(pages)
/
/car/info
and two components
- Header
- CarInput
i used context to maintain the state and pass it to both the pages.
when im in route /car/info
and i change the state using input , the updated state gets displayed in Header component of the same route(page).
But when i go to /
route(page) the state is not updated .i inspected using react dev tools and the context doesnt have the updated values .
Even when i go back to /car/info
, the updated state is not there too. As soon as i transition to /
from /car/info
the state goes back to intialState .
Steps to recreate the same on sandbox
- click on "go to add car"
- enter a car name in the input and click add
- click on "go to home"
Now you can see the car you added is not present there .
UPDATE : As pointed out in the answers below , i was updating the localState . i fixed the code to use global state and yet the problem persists .
New SandBox : https://codesandbox.io/s/inspiring-pond-mp134?file=/context/cars-context.js
when doing a page transition in next.js, the context gets unmounted .
So , Wrapping the context provider in __app.js page makes sure it doesn't get unmounted when doing transition .