- Animation
- Bootstrap
- Button
- Components
- Conditional rendering
- Context API
- Debounce
- Error boundary
- Events
- Form
- Fragment
- Hooks
- Inline styling
- Key
- Lazy loading
- Lifecycle methods
- Portal
- Prop types
- Props
- Redux library
- Ref
- Router
- State
- State management
- Strict mode
- Suspense
- useCallback Hook
- useEffect hook
- useMemo hook
- useReducer hook
- useRef hook
- Virtual DOM
REACT
React Redux Library: Syntax, Usage, and Examples
React Redux
is the official state management binding for React applications using Redux. It allows you to manage and centralize application state in a predictable way, especially useful in large or complex React apps with many components needing shared state.
How to Use React Redux
To use redux React
, you need to install two packages: redux
and react-redux
. The Redux package manages the store, reducers, and actions. The react-redux
library provides hooks and components that allow React to communicate with the Redux store.
Step 1: Installation
npm install redux react-redux
If you're using modern tooling, you may want to add Redux Toolkit as well:
npm install @reduxjs/toolkit
Step 2: Set Up the Redux Store
// store.js
import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './counterSlice';
const store = configureStore({
reducer: {
counter: counterReducer,
},
});
export default store;
Step 3: Wrap Your App with the Provider
// index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { Provider } from 'react-redux';
import store from './store';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<Provider store={store}>
<App />
</Provider>
);
This gives every component in the app access to the Redux store.
Step 4: Use Redux State and Actions in Components
import { useSelector, useDispatch } from 'react-redux';
import { increment } from './counterSlice';
function Counter() {
const count = useSelector((state) => state.counter.value);
const dispatch = useDispatch();
return (
<div>
<p>Count: {count}</p>
<button onClick={() => dispatch(increment())}>Increment</button>
</div>
);
}
This is a working react redux example
using hooks provided by the React Redux library.
When to Use React Redux
Redux is useful when you need to manage shared state across many components or different parts of the app. Here are some specific scenarios where React redux
can improve structure and reliability.
Global State Management
In medium to large applications, local state with useState
or useReducer
becomes hard to manage. Redux helps maintain a single source of truth.
For instance, authentication, user preferences, or theme settings are often global and used across various components.
Cross-Component Communication
When deeply nested components need access to data from ancestors, Redux eliminates prop drilling. Instead of passing props through multiple layers, components can access state directly via useSelector
.
Predictable State Transitions
Every state change in Redux is intentional, traceable, and testable. This predictability is one of Redux’s biggest strengths. In debugging tools like Redux DevTools, you can even “time-travel” through past states.
Examples of React Redux
These examples illustrate key concepts and common use cases.
Example 1: A Simple Counter App
// counterSlice.js
import { createSlice } from '@reduxjs/toolkit';
const counterSlice = createSlice({
name: 'counter',
initialState: {
value: 0,
},
reducers: {
increment: (state) => {
state.value += 1;
},
},
});
export const { increment } = counterSlice.actions;
export default counterSlice.reducer;
Use this slice in your component as shown earlier. This is one way to create a react redux
app using the Redux Toolkit.
Example 2: Authentication Flow
// authSlice.js
import { createSlice } from '@reduxjs/toolkit';
const authSlice = createSlice({
name: 'auth',
initialState: {
user: null,
},
reducers: {
login: (state, action) => {
state.user = action.payload;
},
logout: (state) => {
state.user = null;
},
},
});
export const { login, logout } = authSlice.actions;
export default authSlice.reducer;
In a header component:
const user = useSelector((state) => state.auth.user);
You can now show or hide content based on whether the user is logged in.
Example 3: Comparing React Context vs Redux
While both Context API and Redux provide ways to pass data through components, their purposes differ.
- React Context: Best for lightweight, infrequent updates such as theme or locale.
- Redux: Better suited for complex state transitions, data caching, and shared state.
For example, state transitions in Redux are centralized and explicit. This makes it easier to reason about and test. The Context API doesn't provide tools like middlewares, devtools, or action logs.
react context vs redux
comparisons often lead to the conclusion: use Redux if your state logic is growing in size, complexity, or number of consumers.
Learn More About Redux React
What is Redux in React?
To answer what is redux in react, it’s a predictable state container. It lets you centralize your app’s state and logic, and enforce a unidirectional data flow. In React, Redux helps break away from complex nested props or scattered local state.
Redux has three core principles:
- Single Source of Truth – One global store holds the entire state of your application.
- State is Read-Only – The only way to change the state is by dispatching an action.
- Changes via Pure Functions – Reducers define how the state is updated in response to actions.
React Redux Toolkit
The react redux toolkit
is now the standard way to write Redux logic. It eliminates boilerplate and includes useful utilities like:
createSlice()
to create reducers and actionsconfigureStore()
to combine reducers with devtools and middlewarecreateAsyncThunk()
to handle async logic like API calls
It significantly simplifies store setup, especially for beginners.
import { configureStore } from '@reduxjs/toolkit';
import someReducer from './someSlice';
const store = configureStore({
reducer: {
some: someReducer,
},
});
This modern approach removes the need for hand-written action types, switch statements, and manual immutability handling.
create a React Redux App from Scratch
To create a react redux
app from scratch, you’d follow these steps:
- Create a React app:
npx create-react-app my-app
- Install dependencies:
npm install redux react-redux @reduxjs/toolkit
- Create your slice and store
- Wrap
<App />
with<Provider>
- Use
useSelector
anduseDispatch
inside your components
This gets you up and running with global state management in minutes.
Common Mistakes and Tips
- Not memoizing selectors: For derived state or complex queries, consider using
reselect
. - Overusing Redux: Not all state needs to be in Redux. Keep UI state like modals or tab selections local with
useState
. - Mutating state: Redux Toolkit uses Immer under the hood to let you write “mutable” logic safely. But be cautious in custom reducers.
- Skipping Redux DevTools: Install the browser extension and integrate it in
configureStore
to inspect state and dispatched actions.
TypeScript with Redux
Redux works well with TypeScript, and Redux Toolkit simplifies typing. Use createSlice
and auto-inferred action types to reduce manual type annotations.
type State = {
value: number;
};
const initialState: State = { value: 0 };
const counterSlice = createSlice({
name: 'counter',
initialState,
reducers: {
increment(state) {
state.value++;
},
},
});
This integrates seamlessly with typed components using useSelector
and useDispatch
.
React Redux
provides a clear structure and scalable approach for managing complex state. With Redux Toolkit and hooks, it's easier than ever to build a modern redux React
app that’s both powerful and maintainable. Whether you're syncing data from APIs, coordinating UI across multiple views, or tracking user sessions, Redux helps you keep everything organized and under control.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.