Reputation: 143
I have a next problem:
I want to track some of field of undefined variable window, but which will be defined in future.
For example, if the inner field of variable window will be changed, I want to do some code.
useEffect(() => {
if (window && window.innerWidth) {
// Do something
}
}, [window.innerWidth])
But next.js and react writes following:
How to achieve this effect? Thanks for any advice.
Upvotes: 0
Views: 2349
Reputation: 2858
This solution will work for your use case.
So we have 2 useEffect
hooks.
The first useEffect
attached an event listener to the window
object. Because the window
is used in a useEffect
hook, it won't be executed on the server-side.
The second useEffect
hook will listen to the state changes on innerWidth
, which is being updated whenever the resize
event happens.
const [innerWidth, setInnerWidth] = useState<number | undefined>();
useEffect(() => {
// Handler to call on window resize
function handleResize() {
setInnerWidth(window.innerWidth);
}
// Add event listener
window.addEventListener('resize', handleResize);
// Call handler right away so state gets updated with initial window size
handleResize();
return () => window.removeEventListener('resize', handleResize);
}, []);
useEffect(() => {
// Handle your changes
console.log(innerWidth);
}, [innerWidth]);
Inspired by this useWindowResize implementation
Upvotes: 2
Reputation:
You can try using process.browser to just execute your command during rendering on the client side only.
if (typeof window !== "undefined") { //client side code }
/*OR TRY THIS */
/*Remove dependency array*/
useEffect(() => {
if (window && window.innerWidth) {
// Do something
}
}, [])
Upvotes: 0