-
-
Notifications
You must be signed in to change notification settings - Fork 41
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
Can cause hydration mismatch with SSR #23
Comments
Hi. I started thinking about this topic after the discussion in one of the issues. You can read my thoughts there. I've read the discussions in the links you provided – interesting content. I have one question that I'm confused about: Why the approach with |
Good point. That does avoid the flicker, but results in a warning due to // use-has-hydrated.js
import { useState, useEffect, useLayoutEffect } from "react";
function useHasHydrated(beforePaint = true) {
const [hasHydrated, setHasHydrated] = useState(false);
// To reduce flicker, we use `useLayoutEffect` so that we return value
// before React has painted to the browser.
// React currently throws a warning when using useLayoutEffect on the server so
// we use useEffect on the server (no-op) and useLayoutEffect in the browser.
const isServer = typeof window === "undefined";
const useEffectFn = beforePaint && !isServer ? useLayoutEffect : useEffect;
useEffectFn(() => {
setHasHydrated(true);
}, []);
return hasHydrated;
}
// use-last-provider.js
const defaultValue = "facebook";
const useLastProviderBase = createLocalStorageStateHook("lastAuthProvider", defaultValue);
const useLastProvider = () => {
const [lastProvider, setLastProvider] = useLastProviderBase();
const hasHydrated = useHasHydrated();
// We only return the stored provider value after the app has hydrated
// so that it's undefined on both the server and (initially) the client.
// This allows React to properly hydrate from server and the component
// calling this hook doesn't have to worry about it.
return [hasHydrated ? lastProvider : defaultValue, setLastProvider];
}; Do you think it would make sense to have an options arg for const useLastProvider = createLocalStorageStateHook("lastAuthProvider", "facebook", { ssr: true }); |
I like the approach. I will experiment with it and see if I can add an additional hook to the library. BTW have you tried using |
I didn't know about that, thanks! That seems to work fine for text content, but the issue is that there can be weird rendering bugs when hydration doesn't match, such as elements in the wrong place. Also worth checking out the Material UI useMediaQuery hook. It does an extra render by default to solve this problem and has a |
@gragland I am now convinced that I should find a solution to this. I will think about it and let you know. Thanks for the entire discussion. |
I found a solution I like. A hook called const [todos, setTodos, isPersistent] = useSsrMismatch({
beforeHydration: [defaultTodos, () => {}, true],
afterHydration: useLocalStorageState('todos', defaultTodos)
}) @gragland What do you think? There are some questions I still don't have answers to:
|
I really like the idea for I think my preference would still be to have this integrated into the library and have it be opt-out like Material UI's So maybe the API would look like: // disable ssr support
useLocalStorageState('todos', defaultTodos, { noSsr: true });
// or
const useTodos = createLocalStorageStateHook('todos', defaultTodos, { noSsr: true }); The logic being that Next.js and Gatsby are growing in popularity and it's better that a non-SSR user have an unnecessary re-render than having SSR users run into subtle bugs or have to understand how to use |
Did this get anywhere? I'm also running into the same problem. I like the noSsr feature suggested above and I also agree that it would be good to include it in the library so that developers don't have to go out of their way to "fix" the issue when using NextJS or Gatsby and could flick an option on instead :) |
The current state is — I like the idea and I am willing to implement it. I will post here when I start working on it. |
I have form state persisted with useLocalStorage + SSR. The server was initializing the form with the initial state, and the form wasn't updating until the first interaction, since React wasn't re-rendering until a client-side state change. This could probably be fixed by a forced re-render when the component mounts, but I chose instead to lazily wait to render the whole element when the page loaded. I did the following: const useIsServer = () => {
const [isServer, setIsServer] = useState(typeof window === 'undefined');
useEffect(() => {
if (isServer) setIsServer(false);
}, [isServer]);
return isServer;
};
const MyComponent = () => {
const isServer = useIsServer();
return <>
{/* stuff */}
{isServer ? null : <LazyComponent />}
</>
} This concept could be combined into the main API. I think this type of solution may work without causing an extra render on the client. The API could be: useLocalStorageState(name, initialValue?, serverValue?); Where I have those marked as optional for backwards compatibility. I do see advantages to making There is also the case of React Native, which I didn't test. I'm not that familiar with RN development, so I'm not sure if it's important to include in an API like this. |
@chrbala You are proposing instead of having If yes, I am wondering why not just use |
Yeah, that's what I was thinking. That may not be the optimal API though. The main thing for me is that it's not clear exactly what
The main things I'd look for are:
|
Nice. I believe in the idea that the right questions lead you to the correct answers. Those are very good questions. Thank you! |
I started working on this. If you are one of the people who is waiting for this, you can upvote this comment. |
I've created a draft implementation — 2bcbc52. However, I will need some feedback. Any willing to take a look at it? I am wondering about:
|
@astoilkov I tried the draft implementation in my project just to test it and was able to get it working
I know this is a draft, but export const createSsrLocalStorageStateHook: typeof createLocalStorageStateHook = (...args) =>
withSsr(createLocalStorageStateHook(...args)); Really cool to find you working on this the same day I ran into the mismatch problem. |
Yes, I will try to think of better ones.
Yes. For the apps that don't use server-side rendering.
Perfect. Thanks for this and for all the feedback.
Yes. I will fix this. |
🎉 🎉 🎉I'm ready and I've published a pre-release of the new version. The new version is a complete rewrite. I will explain in detail why I decided to make the change after I receive some feedback. The new version can be installed by running Any feedback is very much welcome. Thanks! |
I released 14.0.0 with hydration mismatch support. The library is now 30% smaller in size as well. I hope this release makes this local storage hook the most popular 😇. Closing this issue. Thanks to all who participated and helped. |
That's brilliant and seems to eliminate the flicker altogether on initial render. I'm looking at making the following React Context and wrapping an entire SSG NextJS app in its Provider: const IsHydratedContext = createContext(false);
export const IsHydratedProvider = ({ children }: { children: ReactNode }) => {
const [isHydrated, setIsHydrated] = useState(false);
const useEffectFn =
typeof window === 'undefined' ? useEffect : useLayoutEffect;
useEffectFn(() => {
setIsHydrated(true);
}, []);
return (
<IsHydratedContext.Provider value={isHydrated}>
{children}
</IsHydratedContext.Provider>
);
};
export const useIsHydrated = () => useContext(IsHydratedContext); Solves the server-vs-client thing efficiently—i.e., globally, immediately, and in a way that forces only the Context-subscribed components to re-render—and the hook doubles as a convenient "is-JS-enabled" flag, making it easy to improve the UX for users who have JS disabled. The |
Hm, I think I spoke too soon: the |
@astoilkov Sorry for the confusion—yes, I saw that part of the discussion, but I'm not actually using your hook. I just stumbled on this thread when researching the problem. My use-case is setting up a single app-wide flag for checking server-vs-client on an SSG NextJS site. |
First off, really nice hook! One issue I'm seeing for SSR'ed apps is if the stored value affects DOM structure then there's going to be a hydration mismatch warning (for example
Warning: Expected server HTML to contain a matching <div> in <div>
).One workaround:
Maybe we can include a section in the readme that covers this? I'm not sure if there's an elegant way for the to hook to handle this. It could wait until mount to return the value from storage, but then that means an extra re-render for non-SSR apps. Thoughts?
More discussion:
https://twitter.com/gabe_ragland/status/1232055916033273858
https://www.joshwcomeau.com/react/the-perils-of-rehydration/
The text was updated successfully, but these errors were encountered: