Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid unnecessary router subscribes #10409

Merged
merged 3 commits into from
Apr 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/silent-stingrays-boil.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"react-router": patch
---

Avoid uneccesary unsubscribe/resubscribes on router state changes
1 change: 1 addition & 0 deletions contributors.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
- akamfoad
- alany411
- alberto
- alexandernanberg
- alexlbr
- AmRo045
- amsal
Expand Down
11 changes: 2 additions & 9 deletions packages/react-router/lib/components.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -57,17 +57,10 @@ export function RouterProvider({
fallbackElement,
router,
}: RouterProviderProps): React.ReactElement {
let [state, setState] = React.useState(router.state);

// Need to use a layout effect here so we are subscribed early enough to
// pick up on any render-driven redirects/navigations (useEffect/<Navigate>)
React.useLayoutEffect(() => {
return router.subscribe((newState) => {
if (newState !== state) {
setState(newState);
}
});
}, [router, state]);
let [state, setState] = React.useState(router.state);
React.useLayoutEffect(() => router.subscribe(setState), [router, setState]);
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No need to check for identity since router.subscribe won't fire unless it changes (and React will bail out if it's the same anyway - https://reacttraining.com/blog/state-in-react-is-immutable)


let navigator = React.useMemo((): Navigator => {
return {
Expand Down