Improved performance for useMediaQuery#435
Improved performance for useMediaQuery#435Profesor08 wants to merge 2 commits intosiberiacancode:mainfrom
useMediaQuery#435Conversation
useMediaQuery
|
Hi @Profesor08 ! Thank you for your PR! Great job analyzing the problem and proposing optimizations for useMediaQuery. I completely understand your desire to improve performance by eliminating multiple matchMedia calls and redundant subscriptions. You're absolutely right — the current implementation isn't ideal, and the problems you described are real. But here's my main thought — I want to keep the library as simple as possible. Such optimizations aren't necessary for every project, and not every user needs them. However, I really like your idea. That's why I'm thinking about creating a createSharedHook utility. This approach gives us two important benefits: We don't need to rewrite every hook manually — once we create the utility, we can use it where optimizations are really needed Developers can choose — those who need maximum performance can use hooks built with createSharedHook, while others can stick with the simple implementation So instead of merging the PR right now, I suggest we:
Your contribution is very valuable — it highlighted an important problem and pushed us to think about a universal solution. Thanks for helping improve the library! |
export const useSharedMediaQuery = createSharedHook(useMediaQuery);
console.log("@", useSharedMediaQuery);
const First = () => {
const matches = useSharedMediaQuery("(max-width: 768px)");
return (
<div>
This is <code>{matches ? "mobile" : "desktop"}</code> screen
</div>
);
};
const Second = () => {
const matches = useSharedMediaQuery("(max-width: 768px)");
return (
<div>
This is <code>{matches ? "mobile" : "desktop"}</code> screen
</div>
);
};
const Demo = () => {
return (
<div>
<First />
<Second />
</div>
);
};Prototype already done, i need fix some dx moments and add test |
Optimize
useMediaQuery, add shared stores and single listener per queryCurrent implementation has some problems
Every
useMediaQueryinstance maintain's its own MediaQueryList and change listener. With multiple components subscribing to the same query this meant:Solution
A module-level Map cache now stores a single MediaQueryListStore per unique query string, shared across all subscribers.