herecydev / gatsby-plugin-internationalization

Gatsby plugin for statically generating i18n pages with zero effort
4 stars 0 forks source link

useLocalization data is not reactive #49

Open cmrd-senya opened 3 years ago

cmrd-senya commented 3 years ago

The plugin provides React hook useLocalization. It is used like this:

const { locale, defaultLocale, locales, localizedNavigate } = useLocalization()

However these values are not reactive, e.g. locale value. If I navigate to localized url from /en/slug to /fr/slugusing the usual Gatsby Link components, the page is being routed to the new address without reload but locale value remains the same it was before - en in my example while URL is /fr/slug already. My expectation is that locale value coming from the hook is changed reactively as the page is navigated to other language URLs.

This happens because the values are cached with useState here: https://github.com/herecydev/gatsby-plugin-internationalization/blob/3d69bd3189eeb13e5509a91440b53133d0bb3034/src/LocalizationContext.js#L17

But the value that comes from pageContext is actually reactive and changes as URL changes:

const { locale, defaultLocale, locales } = pageContext;

So in theory it's not a problem to fix that and pass locale down without caching. So is there any particular reason to cache it not update as locale from pageContext updates?

herecydev commented 3 years ago

That seems like a massive oversight, the correct fix would be to use useMemo I think. That preserves the caching but will invalidate when locale changes. I think Gatsby has this built in now, which is why I'm not actively working on this anymore

cmrd-senya commented 3 years ago

@herecydev I'm not aware of it being built in in Gatsby. If you know where to learn about please give a reference.

Gatsby official docs recommend using this plugin with the same purpose and unfortunately similar name: https://github.com/angeloocana/gatsby-plugin-i18n

However I don't really like the convention they used in that plugin, where the localized files have to be created one copy per locale. That's why I was looking for alternative and ended up using your plugin instead of the one from the doc.

But I don't know too much about Gatsby so maybe I'm missing some major piece here. However as for what it seems to me know your plugin is a viable and meaningful alternative to the plugin from the official docs so maybe could potentially be mentioned there along with the other one.