After installing and setting up Redux Tool-kit on your Next.js app
1. Use Redux in Your Components
we can now access the Redux store and dispatch actions from any component.
// pages/index.js
import { useSelector, useDispatch } from 'react-redux';
import { increment, decrement } from '../features/counterSlice';
export default function Home() {
const count = useSelector((state) => state.counter.value);
const dispatch = useDispatch();
return (
<div>
<h1>Count: {count}</h1>
<button onClick={() => dispatch(increment())}>Increment</button>
<button onClick={() => dispatch(decrement())}>Decrement</button>
</div>
);
}
2. Server-Side Rendering with Redux (Optional)
If we need to use Redux with Next.js’s server-side rendering (SSR), we can use getServerSideProps or getStaticProps. we’ll need to dispatch actions inside these functions and then pass the state to the component.
Example:
// pages/index.js
import { useSelector } from 'react-redux';
import { increment } from '../features/counterSlice';
import { store } from '../store/store';
import { Provider } from 'react-redux';
export default function Home() {
const count = useSelector((state) => state.counter.value);
return (
<div>
<h1>Count: {count}</h1>
<button onClick={() => dispatch(increment())}>Increment</button>
</div>
);
}
export async function getServerSideProps() {
// Simulate an action dispatch for SSR
store.dispatch(increment());
return {
props: {},
};
}