Search code examples
reactjsnext.jsredux

ReferenceError: window is not defined in redux component


import { createSlice } from "@reduxjs/toolkit";

const initialState = {
  value: window.innerWidth
};

const screenSizeSlice = createSlice({
  name: 'screenSize',
  initialState,
  reducers: {    
    screenSizeResize: (state, actions) => {
      state.value = actions.payload
    },
  }
})

export const {screenSizeResize } = screenSizeSlice.actions

export default screenSizeSlice.reducer   

So I have this component, and I have this error:

ReferenceError: window is not defined

If I use typeof window !== 'undefined' for example to solve it, it will cause hydration. I'm using nextjs btw.

How to solve this problem?

I tried conditional rendering but it caused hydration.


Solution

  • When the app starts, we don't have the window object yet. Because it is only available after the component mounts. So, I would say you have to move that code into useEffect() or if you are using class-based components, move to componentDidMount()

    For the Functional Component.

    import { createSlice } from "@reduxjs/toolkit";
    
    const initialState = {
      value: ""
    };
    
    const screenSizeSlice = createSlice({
      name: 'screenSize',
      initialState,
      reducers: {    
        screenSizeResize: (state, actions) => {
          state.value = actions.payload
        },
      }
    })
    
    export const {screenSizeResize } = screenSizeSlice.actions
    
    export default screenSizeSlice.reducer 
    

    Give it an empty value at first and when the app mounts that in the App.js, inside an useEffect set this value.

    const { screenSizeResize } = useSelector(screenSizeSlice)
    
    useEffect(() => {
       screenSizeResize(size)
    })
    

    I guess this will work, inform me if it worked.