I'm using NextJS and hydration and am getting this error when I try to conditionally display my wakelock component based on browser support (the <div>
in question is my wakelock component):
import styles from "./wakelock.module.scss";
import { useWakeLock } from 'react-screen-wake-lock';
export default function Wakelock() {
const {
isSupported,
released,
request,
release
} = useWakeLock();
return (
<>
{isSupported && (
<div className={ styles['wakelock'] }>
<input
type="checkbox"
checked={ !released ? true : false }
name="wakelock"
id="wakelock"
onChange={ () => (!released ? release() : request()) }
/>
<label htmlFor="wakelock">Prevent Sleep</label>
</div>
)}
</>
)
}
I had to deal with this when I was trying to do a DIY implementation of the WakeLock API. When NextJS pre-renders the page on the server there is no browser so isSupported
is always false
, therefore the JSX doesn't render. So I created an isSupported
state variable, then ran a support check inside a useEffect
call which runs after the initial render and updates the state to true
, if applicable.
I'm not exactly sure how to handle this using your package though since you can't call hooks inside useEffect.
Would appreciate some suggestions. Thanks!