0

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") || "{}"))
}, [])

1 Answer 1

0
const [string, setString] = useState<string>("default")
// define default value

useEffect(()=>{
   localStorage.getItem("stored-string") || "default"
}, [])

Is this solution works ?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.