Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Why the double useMemo? #16

Closed
wmertens opened this issue Nov 9, 2019 · 4 comments · Fixed by #17
Closed

Why the double useMemo? #16

wmertens opened this issue Nov 9, 2019 · 4 comments · Fixed by #17

Comments

@wmertens
Copy link
Contributor

wmertens commented Nov 9, 2019

I don't understand this code:

return useMemo(() => Object.assign(Object.values(useSSRObject), useSSRObject), [whereAmI])

  const useSSRObject = useMemo(() => ({
    isBrowser: whereAmI === BROWSER,
    isServer: whereAmI === SERVER,
    isNative: whereAmI === NATIVE,
    canUseWorkers: typeof Worker !== 'undefined',
    canUseEventListeners: whereAmI === BROWSER && !!window.addEventListener,
    canUseViewport: whereAmI === BROWSER && !!window.screen
  }), [whereAmI])

  return useMemo(() => Object.assign(Object.values(useSSRObject), useSSRObject), [whereAmI])

First it creates useSSRObject, which seems like it should be sufficient, and then it creates an array of the values that also looks like useSSRObject?

Also, all these values are static, so they could just be exported from a module without all the hooks?

@wmertens
Copy link
Contributor Author

wmertens commented Nov 9, 2019

ah ok, the array+object is to allow both [isBrowser, isServer, ...] and direct property access. Still, that could be done in the first useMemo, no?

Another observation: how about just exporting the static values, and a function that you can call on the server to set isServer:true? That way, there's no guesswork and no hooks needed?

@alex-cory
Copy link
Owner

When would we need to explicitly set isServer to true?

@alex-cory
Copy link
Owner

Honestly, it's probably an overuse of useMemo.

@wmertens
Copy link
Contributor Author

Ah, I didn't get around to commenting yet - actually for hydration it should be possible to turn on isServer and then turn it off. Coincidentally, there's a discussion at GoogleChromeLabs/react-adaptive-hooks#18 on how to do this best.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants