synacor / preact-i18n

Simple localization for Preact.
BSD 3-Clause "New" or "Revised" License
205 stars 18 forks source link

useContext hook returns new reference every time it is called #62

Open sitaram-mulik-synacor opened 9 months ago

sitaram-mulik-synacor commented 9 months ago

useContext hook with IntlContext creates an object with a new reference from the passed props every time it's called.

Problem: If we use this hook directly or indirectly through any other hook inside a component which is getting iterated over a loop, results in performance issues due to unnecessary rendering.

Solution: I think the ideal solution for this problem would be to replace the existing logic of the IntlProvider component (which uses local variables with new reference derived from the props passed) with a component state and pass it as context value. This way we can make use of useEffect hook for side effect logics like merging the properties of definition prop. Other approach could be to make use of useMemo hook, but that way we can not run separate logic based on different side effects.

Slackblitz link where the issue is reproducible: https://stackblitz.com/edit/preact-starter-template-6lb3ag?file=index.js

PR https://github.com/synacor/preact-i18n/pull/63