Blog>
Snippets

Connecting createReducer to React Functional Components with Hooks

Show a functional React component using hooks like `useSelector` and `useDispatch` to interact with a store managed by a reducer created with createReducer.
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { decrement, increment } from './counterSlice';

// Functional Component
const CounterComponent = () => {
  // Accessing state from store
  const count = useSelector((state) => state.counter.value);
  // Setting up dispatch function
  const dispatch = useDispatch();

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

export default CounterComponent;
This component uses the useSelector hook to read counter's slice of state from the Redux store and the useDispatch hook to dispatch actions to update that state. The increment and decrement actions are imported from counterSlice, which is assumed to be generated by createReducer or createSlice.