Next.js Discord

Discord Forum

Component marked with "use client" still run on server

Answered
West African Crocodile posted this in #help-forum
Open in Discord
West African CrocodileOP
Hi, I am building an application with Nextjs 14 app router. I have built a hook that accesses local storage.
I have marked the hook with "use client" in the top, and the component that uses the hook is also a client component. I get an error saying that localStorage is not defined.
Here is my code:
'use client'; import { useState } from 'react'; const ListKey = 'clickedProjectIds'; const getList = () => { return JSON.parse(localStorage.getItem(ListKey) || '[]'); }; export const useClickedProjects = () => { const [ids, setIds] = useState(getList()); const setIdClicked = (id: string) => { const currentList = getList(); currentList.push(id); localStorage.setItem(ListKey, JSON.stringify(currentList)); setIds(currentList); }; return { isClicked: (id: string) => ids.includes(id), setIdClicked, }; };
Answered by Giant panda
That is expected, client components are still prerendered on the server for SEO purposes. Use an effect to deal with this correctly.
View full answer

1 Reply

Giant panda
That is expected, client components are still prerendered on the server for SEO purposes. Use an effect to deal with this correctly.
Answer