Flat Preloader Icon

Using Redux with React

Redux is a state management library commonly used with React to manage the state of your application in a predictable way. Here’s a basic overview of how you can use Redux with React:

1. Install Redux and React-Redux

First, you need to install Redux and React-Redux. React-Redux is the official React bindings for Redux.
				
					npm install redux react-redux

				
			

2. Create a Redux Store

The Redux store holds the state of your application. You create it using the createStore function from Redux. You’ll also need to define a reducer that specifies how the state changes in response to actions.

store.js:

				
					import { createStore } from 'redux';

// Define your initial state
const initialState = {
  count: 0
};

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

// Create the Redux store
const store = createStore(reducer);

export default store;

				
			

3. Provide the Store to Your React Application

You need to use the component from React-Redux to make the store available to your React components.

index.js:

				
					import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import store from './store';
import App from './App';

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);

				
			

4. Connect React Components to Redux

Use the useSelector and useDispatch hooks from React-Redux to read from the Redux store and dispatch actions.

App.js:

				
					import React from 'react';
import { useSelector, useDispatch } from 'react-redux';

const App = () => {
  const count = useSelector((state) => state.count);
  const dispatch = useDispatch();

  return (
    <div>
      <h1>Count: {count}</h1>
      <button onClick={() => dispatch({ type: 'INCREMENT' })}>Increment</button>
      <button onClick={() => dispatch({ type: 'DECREMENT' })}>Decrement</button>
    </div>
  );
};

export default App;

				
			

Key Concepts

  • Actions: Plain JavaScript objects that describe what happened. They have a type property and optionally some payload.
  • Reducers: Functions that specify how the state changes in response to an action.
  • Store: The object that holds the application state and provides methods to access the state, dispatch actions, and register listeners.