What is Redux in React: Simple Explanation and Example
Redux is a tool used with React to manage app data in one place called a store. It helps keep data organized and easy to update across many parts of your app.How It Works
Imagine your React app is like a big office with many rooms (components). Each room needs some information to work properly. Without Redux, each room might keep its own notes, which can get messy and confusing.
Redux acts like a central filing cabinet (called the store) where all important information is kept. When a room needs data, it asks the filing cabinet. When something changes, the filing cabinet updates the notes and tells all rooms to check the new info.
This way, everyone in the office always has the latest information, and you don’t have to run around passing notes. Redux uses simple rules: you send a message (an action) saying what changed, and a special helper (a reducer) updates the filing cabinet safely.
Example
This example shows a simple React app using Redux to count clicks. The count is stored in Redux, and clicking the button updates it everywhere.
import React from 'react'; import { createStore } from 'redux'; import { Provider, useSelector, useDispatch } from 'react-redux'; // Reducer: updates state based on action const counterReducer = (state = { count: 0 }, action) => { switch (action.type) { case 'increment': return { count: state.count + 1 }; default: return state; } }; // Create Redux store const store = createStore(counterReducer); // React component using Redux state and dispatch function Counter() { const count = useSelector(state => state.count); const dispatch = useDispatch(); return ( <div> <p>Count: {count}</p> <button onClick={() => dispatch({ type: 'increment' })}> Click me </button> </div> ); } // App with Redux Provider export default function App() { return ( <Provider store={store}> <Counter /> </Provider> ); }
When to Use
Use Redux when your React app has many components that need to share and update the same data. It helps avoid confusion and bugs from passing data through many layers.
For example, in a shopping app, Redux can keep track of the cart items so any part of the app can show or update the cart easily. It’s also helpful when you want to keep data consistent after page reloads or across different screens.
If your app is small or simple, Redux might be more than you need. But for medium to large apps with complex data flows, Redux makes managing state clearer and more predictable.
Key Points
- Redux centralizes state: All app data lives in one place called the store.
- State changes are predictable: You send actions and reducers update state.
- Works well with React: React components can read and update Redux state easily.
- Good for complex apps: Helps manage shared data across many components.
- Not always needed: For simple apps, React’s built-in state may be enough.