#useOs custom hook causes Client Server state mismatch.

4 messages · Page 1 of 1 (latest)

zealous sluice
glass mica
#

is it a server component or client component ?

zealous sluice
#

Using NextJS 13 without /app directory and the page is SSRed

reef frigate
#

Ok, so useOs hasnt been written in a way to prevent SSR hydration errors. The issue here is that the value on the server will be "undetermined" and on the first render on the client it will be whatever getOs returns.

One solution would be to set the value in useEffect

// import this as a simple function instead of a hook
// we can do that because it doesnt use any hooks itself
import { useOs as getOs } from "mantime";

const Comp = () => {
  // same value for client and server
  const [os, setOs] = useState("undetermined");
  
  // useEffect only runs on the client so no hydration issues here
  useEffect(() => {
    setOs(getOs());
  }, []);
}