Skip to content

Commit

Permalink
Use more performant way to compare objs.
Browse files Browse the repository at this point in the history
  • Loading branch information
molefrog committed Jun 24, 2024
1 parent db328be commit db20a6e
Showing 1 changed file with 8 additions and 4 deletions.
12 changes: 8 additions & 4 deletions packages/wouter/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -192,10 +192,13 @@ const h_route = ({ children, component }, params) => {
return typeof children === "function" ? children(params) : children;
};

const useCachedParams = (value, comp = JSON.stringify) => {
const prev = useRef(Params0);
return (prev.current =
comp(value) === comp(prev.current) ? prev.current : value);
// a hook to cache the params object between renders (if they are shallow equal)
const useCachedParams = (value) => {
let prev = useRef(Params0),
curr = prev.current;

for (const k in value) if (value[k] !== curr[k]) curr = value;
return (prev.current = curr);
};

export const Route = ({ path, nest, match, ...renderProps }) => {
Expand All @@ -208,6 +211,7 @@ export const Route = ({ path, nest, match, ...renderProps }) => {
match ?? matchRoute(router.parser, path, location, nest);

const params = useCachedParams({ ...useParams(), ...routeParams });

if (!matches) return null;

const children = base
Expand Down

0 comments on commit db20a6e

Please sign in to comment.