Blog>
Snippets

Using RTK 2.0 with React Hooks (useDispatch, useSelector)

Provide examples of using RTK 2.0 with React hooks like useDispatch and useSelector to interact with Redux store state in functional React components.
import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './counterSlice';

export const store = configureStore({
  reducer: {
    counter: counterReducer,
  },
});
This is the setup of the Redux store using RTK's configureStore function. The counterReducer is a slice reducer that will handle updating the state for counter-related actions.
import { createSlice } from '@reduxjs/toolkit';

export const counterSlice = createSlice({
  name: 'counter',
  initialState: {
    value: 0,
  },
  reducers: {
    incremented: state => {
      state.value += 1;
    },
    decremented: state => {
      state.value -= 1;
    },
  },
});

export const { incremented, decremented } = counterSlice.actions;

export default counterSlice.reducer;
This is a counter slice created using RTK's createSlice function. It defines the initial state, and two reducers (incremented and decremented) to handle changes to the state.
import { Provider } from 'react-redux';
import { store } from './store';
import CounterComponent from './CounterComponent';

function App() {
  return (
    <Provider store={store}>
      <CounterComponent />
    </Provider>
  );
}

export default App;
This is the integration of the Redux store into the React application using the Provider component from react-redux. It makes the store available to any nested components.
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { incremented, decremented } from './counterSlice';

function CounterComponent() {
  const count = useSelector(state => state.counter.value);
  const dispatch = useDispatch();

  return (
    <div>
      <div>Count: {count}</div>
      <button onClick={() => dispatch(incremented())}>Increment</button>
      <button onClick={() => dispatch(decremented())}>Decrement</button>
    </div>
  );
}

export default CounterComponent;
This is a CounterComponent that uses the useDispatch and useSelector hooks. useDispatch allows the component to dispatch actions to the store, and useSelector allows it to read a specific value from the store's state.