cf.completefrontend

Write the codeMedium

Write a useHydrated hook

Write useHydrated(). It returns false during server rendering and while React hydrates the server's HTML, and true once the page has hydrated, so a component can show browser-only values without a hydration mismatch.

Components that mount later, after the page has hydrated, or in an app rendered only in the browser with createRoot, must get true on their very first render, with no extra render showing the server's version.

function SavedTeas() {
  const hydrated = useHydrated();
  if (!hydrated) return <p>Loading saved teas</p>;
  return <p>Saved teas: {JSON.parse(localStorage.getItem("saved") ?? "[]").length}</p>;
}
Write this (useHydrated.js)
import { useEffect, useState, useSyncExternalStore } from "react";
 
export function useHydrated() {
  // Return false on the server and while hydrating, true after.
  return false;
}
The checks your code must pass
  • returns true in an app rendered only in the browser
  • is true from the first render when nothing is hydrated
  • is false while hydrating, then true
  • hydrates without a mismatch, keeping the server's elements
  • is true on the first render of a component mounted after hydration

The answer

Write it yourself first. Then compare it with a reference solution and the checks it passes.

Checking your sign-in…