Blog>
Snippets

Integrating Redux Toolkit with React Hooks

Showcase how to use the useSelector and useDispatch hooks provided by React-Redux with Redux Toolkit's configureStore, highlighting the elimination of connect and mapStateToProps.
import { configureStore } from '@reduxjs/toolkit';
import { Provider } from 'react-redux';
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import counterReducer from './features/counter/counterSlice';

// Configure the store with slices
const store = configureStore({
  reducer: {
    counter: counterReducer,
  },
});

ReactDOM.render(
  <React.StrictMode>
    <Provider store={store}>
      <App />
    </Provider>
  </React.StrictMode>,
  document.getElementById('root')
);
This snippet sets up the Redux store using Redux Toolkit's configureStore and wraps the App component with the Redux Provider to make the store available to the entire application.
import { createSlice } from '@reduxjs/toolkit';

// Create a counter slice with its reducers
export const counterSlice = createSlice({
  name: 'counter',
  initialState: {
    value: 0
  },
  reducers: {
    increment: state => {
      state.value += 1;
    },
    decrement: state => {
      state.value -= 1;
    }
  }
});

export const { increment, decrement } = counterSlice.actions;

export default counterSlice.reducer;
This snippet creates a counter slice that includes actions and reducers to increment and decrement a value, using Redux Toolkit's createSlice.
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { increment, decrement } from './features/counter/counterSlice';

function Counter() {
  // Access the Redux state using useSelector
  const count = useSelector(state => state.counter.value);

  // Get the dispatch function with useDispatch
  const dispatch = useDispatch();

  return (
    <div>
      <span>{count}</span>
      <button onClick={() => dispatch(increment())}>Increment</button>
      <button onClick={() => dispatch(decrement())}>Decrement</button>
    </div>
  );
}

export default Counter;
This component acts as a counter which uses useSelector to read the current count value from the Redux store and useDispatch to dispatch actions that will update the store.