Understanding action.payload in React useReducer

💡 Understanding action.payload in React useReducer When learning useReducer in React, one concept that often confuses beginners is action.payload. Once you understand it, your state management becomes much clearer. Let’s break it down simply. 📌 The Structure of an Action In useReducer, when we want to update state, we dispatch an action. An action is usually an object with two main properties: dispatch({ type: "deposit", payload: 100 }); type → describes what happened payload → contains the data needed to update the state Think of it like sending a message: 👉 type = the instruction 👉 payload = the information needed to execute that instruction 📌 Example in a Reducer function reducer(state, action) { switch (action.type) { case "deposit": return { ...state, balance: state.balance + action.payload }; case "withdraw": return { ...state, balance: state.balance - action.payload }; default: throw new Error("Unknown action"); } } When we dispatch: dispatch({ type: "deposit", payload: 200 }); The reducer receives the action and uses action.payload (200) to update the balance. 📌 Why payload Matters Without payload, the reducer wouldn't know what data to use when updating the state. payload can contain: Numbers Strings Objects Arrays Example: dispatch({ type: "addUser", payload: { name: "Tobi", role: "Developer" } }); 🚀 Key Takeaway A simple way to remember this: action.type → What happened action.payload → The data needed to handle it Understanding this pattern makes useReducer far more powerful and helps you write cleaner and more predictable state logic in React. 💬 What concepts in React took you the longest to understand when you started? #React #JavaScript #FrontendDevelopment #ReactHooks #WebDevelopment #LearningInPublic

To view or add a comment, sign in

Explore content categories