Next.js Discord

Discord Forum

used `use client` but still get error in the terminal

Answered
Samyar posted this in #help-forum
Open in Discord
I used use client but when i want to use browser apis it gives me errors only in terminal (not the browser)

in the browser i have no problem and the app functions without problem

but since i have used use client shouldn't it be rendered on the client why do i get the bellow error in the terminal ? should i be worried about it ?

- warn Fast Refresh had to perform a full reload due to a runtime error.
- error components\layout\header.tsx (29:42) @ window
- error ReferenceError: window is not defined
    at eval (./components/layout/header.tsx:65:137)
    at Array.map (<anonymous>)
    at children (./components/layout/header.tsx:62:110)
  27 |                         <Link
  28 |                           className={classNames(
> 29 |                             item.href === window.location.hash
     |                                          ^
  30 |                               ? 'bg-gray-900 text-white'
  31 |                               : 'text-gray-300 hover:bg-gray-700 hover:text-white',
  32 |                             'px-3 py-2 rounded-md text-sm font-medium'
Answered by joulev
client components are still prerendered on the server; you can only access window in useEffect, event handler and similar places
View full answer

3 Replies

Answer
@joulev client components are still prerendered on the server; you can only access `window` in `useEffect`, event handler and similar places
great thank you
but what if i wanted to use it somewhere else what can i do in that case ?
i have make a state and change it in useEffect ?
@Samyar great thank you but what if i wanted to use it somewhere else what can i do in that case ? i have make a state and change it in useEffect ?
for your case just make a state
const [hash, setHash] = useState("");
useEffect(() => {
  setHash(window.location.hash);
}, []);