I understand that this question has been asked several times but my example doesn’t suffer from any of the solutions provided in the other examples. I hope someone can help, thanks in advance.
Here’s my slice, screenSlice.js:
import { createSlice } from '@reduxjs/toolkit';
//this slice sets the state of the screens Y axis
export const screenSlice = createSlice({
name: 'screenYPlacement',
initialState: {
offsetY: 0,
},
reducers: {
setoffsetY: (state, action) => {
return {
...state,
offsetY : action.payload
}
}
}
});
export const { setoffsetY } = screenSlice.actions
export default screenSlice.reducer
My store, store.js :
import { configureStore } from '@reduxjs/toolkit';
import screenReducer from './screenSlice';
export default configureStore({
reducer: {
offsetY: screenReducer
},
});
The file in which it is called, app.js:
import React, { useEffect} from 'react'
import './App.scss';
import { useDispatch } from 'react-redux';
import { setoffsetY } from './redux/screenSlice';
import Header from './components/header/Header';
import Hero from './components/hero/Hero';
function App() {
const dispatch = useDispatch()
//this function will use the redux reducer to save the Y axis to redux
const handleScroll = () => dispatch(setoffsetY(window.pageYOffset));
useEffect(() => {
window.addEventListener('scroll', handleScroll);
return () => window.removeEventListener('scroll', handleScroll);
});
return (
<div className="App">
<Header/>
<Hero/>
</div>
);
}
export default App;