I have a tabular React component in Next.js which uses localStorage to save and restore user's preference of which columns to show and which ones to hide. Naturally, I want the component to load the user's preference before rendering any part of the table.
Using localStorage directly in state variable initialization causes ReferenceError at the server about localStorage being undefined because of SSR.
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>(
JSON.parse(localStorage.getItem("columnVisibility") || "{}"))
Using useEffect to load the preferences takes time and renders the table header before loading them fully, hence showing the default configuration instead of the user-defined one for a moment.
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>()
useEffect(() => {
setColumnVisibility(JSON.parse(localStorage.getItem("columnVisibility") || "{}"))
}, [])