Create Redux Reducer Function in React Js 2025
Create Redux Reducer Function in React JS 2025
Redux reducer ek pure function hota hai jo action ke basis par state ko update karta hai. Ye function 2 cheezein leta hai: pehla current state aur doosra action. Ye new state return karta hai bina original state ko mutate kiye. Chaliye ek example dekhte hain:
1. Redux Reducer Function ka Syntax:
const initialState = {
count: 0
};
function counterReducer(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;
}
}
2. Explanation:
- initialState: Initial value of the state.
- state: Current state passed by Redux.
- action: Object with type and payload (if any).
- switch: Action type ke basis par state change karna.
- return: Hamesha new state return karna chahiye.
3. Redux mein reducer kaise use hota hai?
import { createStore } from 'redux';
import counterReducer from './reducers/counterReducer';
const store = createStore(counterReducer);
export default store;
Ab aap Redux reducer function ko Redux store ke saath connect kar sakte ho aur React component mein state aur dispatch ka use karke usse control kar sakte ho.