React Redux state management

React reducer:

import { useReducer } from 'react';

// Reducer function
const counterReducer = (state, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return { count: state.count + 1 };
    case 'DECREMENT':
      return { count: state.count - 1 };
    default:
      return state;
  }
};

// Counter component
const Counter = ({ dispatch }) => {
  return (
    <div>
      <p>Count: {state.count}</p>
      <button onClick={() => dispatch({ type: 'INCREMENT' })}>Increment</button>
      <button onClick={() => dispatch({ type: 'DECREMENT' })}>Decrement</button>
    </div>
  );
};

// Parent component managing state
const CounterApp = () => {
  const [state, dispatch] = useReducer(counterReducer, { count: 0 });

  return (
    <Counter dispatch={dispatch} />
  );
};

export default CounterApp;

React Redux for state management:

Redux actions:

export const increment = () => ({
  type: 'INCREMENT',
});
export const decrement = () => ({
  type: 'DECREMENT',
});

Redux reducer:

const counterReducer = (state = { count: 0 }, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return { count: state.count + 1 };
    case 'DECREMENT':
      return { count: state.count - 1 };
    default:
      return state;
  }
};
export default counterReducer;

Redux store:

import { createStore } from 'redux';
import counterReducer from './reducer';
const store = createStore(counterReducer);
export default store;

Counter component:

import { useDispatch, useSelector } from 'react-redux';
import { increment, decrement } from './actions';
const Counter = () => {
  const count = useSelector((state) => state.count);
  const dispatch = useDispatch();
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => dispatch(increment())}>Increment</button>
      <button onClick={() => dispatch(decrement())}>Decrement</button>
    </div>
  );
};
export default Counter;

Main App component:

import { Provider } from 'react-redux';
import Counter from './Counter';
import store from './store';
const App = () => {
  return (
    <Provider store={store}>
      <Counter />
    </Provider>
  );
};
export default App;

Leave a Comment