useLocationSelector
Selectively retrieve properties from location. This hook will only re-render when the value you return is changed. For more information, see
useLocationSelector uses useSyncExternalStore to subscribe to window.location changes and lets you extract only the part of the location you care about via a selector function. The component re-renders only when the selected value actually changes, preventing unnecessary updates when other location properties change (e.g., hash changes won’t re-render a component that only selects pathname).
When to Use
- Reading the current pathname, hash, or search params without importing a full routing library
- Optimizing performance by subscribing to only the specific location property your component needs
- Building lightweight navigation-aware components that respond to URL changes
Notes
- SSR-safe: Accepts a
fallbackparameter that is returned during server-side rendering whenwindow.locationis not available. - Selective re-renders: Unlike reading
window.locationdirectly, the selector pattern ensures your component only re-renders when the derived value changes. - Browser events: Listens to
popstateevents onwindowto detect back/forward navigation. Hash changes andpushState/replaceStatecalls are also tracked.
Usage
Live Editor
function CurrentPathname() { const pathname = useLocationSelector(location => location.pathname); const ref = useRef(0); useEffect(() => { ref.current = ref.current + 1; }); return ( <div> {pathname} <div>renderCount: {ref.current}</div> </div> ); } function CurrentHash() { const hash = useLocationSelector(location => location.hash || "nohash"); const ref = useRef(0); useEffect(() => { ref.current = ref.current + 1; }); return ( <div> {hash} <div>hashRender: {ref.current}</div> </div> ); }; function Links() { return ( <div> <a href="#link1">#link1</a> <a href="#link2">#link2</a> <a href="#link3">#link3</a> </div> ); }; function Demo() { return ( <div> <CurrentPathname /> <CurrentHash /> <Links /> </div> ); }; render(<Demo/>);
Result
API
useLocationSelector
Returns
R | undefined
Arguments
| Argument | Description | Type | DefaultValue |
|---|---|---|---|
| selector | selector function | (location: Location) => R (Required) | - |
| fallback | default value | R | undefined | - |