💡 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
Understanding action.payload in React useReducer
More Relevant Posts
-
🚀 React Hooks — Complete Guide (Made Simple) If you’re learning React, you’ve probably heard this advice: 👉 “Master Hooks, and everything becomes easier.” And it’s true. Because Hooks are not just features… they’re the foundation of modern React development. ⸻ 💡 Why Hooks matter: Before Hooks, React development often felt messy: • Class components everywhere • Lifecycle methods hard to manage • Logic scattered and difficult to reuse Now with Hooks 👇 ✔ Cleaner functional components ✔ Reusable and modular logic ✔ Better readability and scalability ⸻ 🧠 Quick breakdown of essential Hooks: 🔹 useState — Manage component state 🔹 useEffect — Handle side effects (API calls, lifecycle) 🔹 useContext — Share global data easily 🔹 useRef — Access DOM & persist values 🔹 useMemo — Optimize expensive calculations 🔹 useCallback — Memoize functions 🔹 Custom Hooks — Reuse logic across components ⸻ ⚡ The real shift: Hooks change how you think. From: ❌ “How do I manage lifecycle?” To: ✅ “How do I structure logic cleanly?” ⸻ 🔥 Pro tip: Don’t just memorize Hooks. 👉 Build projects 👉 Break things 👉 Understand why each Hook exists That’s where real learning happens. ⸻ 💬 Question: Which Hook do you find most confusing (or most useful)? ⸻ 📌 Save this post — it’s a quick reference you’ll keep coming back to. #ReactJS #FrontendDevelopment #WebDevelopment #JavaScript #Coding #Programming #Developers #SoftwareEngineering #ReactHooks #LearnToCode #TechCommunity #BuildInPublic #UIUX #CareerGrowth
To view or add a comment, sign in
-
-
Common React Events Every Developer Should Know If you're learning React, understanding event handling is essential for building interactive user interfaces. Here are some of the most commonly used React events and when to use them. 1. onClick: Triggered when a user clicks an element. Commonly used for buttons, menus, and triggering actions. 2. onChange: Fires when the value of an input field changes. Mostly used in forms to capture user input. 3. onFocus: Occurs when an input field becomes active. Helpful for highlighting fields or showing hints. 4. onBlur: Happens when an input field loses focus. Often used for validation after the user leaves a field. 5. onMouseOver: Executes when the mouse moves over an element. Useful for hover effects, tooltips, or previews. 6. onMouseOut Triggered when the mouse leaves an element. Commonly paired with hover interactions. 7. onSubmit Invoked when a form is submitted. Used to handle form data before sending it to a server. 8. onKeyDown: Triggered when a keyboard key is pressed down. Useful for shortcuts or detecting specific keys. 9. onKeyUp: Fires when a keyboard key is released. Often used for live search or input validation. Why these events matter: React events allow developers to create dynamic and responsive applications by responding to user actions in real time. If you're learning React, mastering these events will make your UI much more interactive and user-friendly. #React #WebDevelopment #FrontendDevelopment #JavaScript #Coding #ReactJS #Programming
To view or add a comment, sign in
-
-
𝗧𝗼𝗽 𝗙𝗿𝗼𝗻𝘁𝗲𝗻𝗱 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻𝘀(2026) Whether you're preparing for your next big opportunity or mentoring others, this list can be a game-changer. 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗯𝗮𝘀𝗲𝗱 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻𝘀 1. Implement `Promise.all` polyfill 2. Implement `Promise.any` polyfill 3. Implement `Array.prototype.reduce` polyfill 4. Implement Lodash’s `flatten` method 5. Implement auto-retry for promises 6. Throttle promises by batching 7. Debouncing implementation 8. Throttling implementation 9. Execute N callback-based async tasks in series 10. Output prediction for tricky 10–15 JavaScript snippets 11. Object vs Map differences in JavaScript 12. Difference between `PATCH` and `PUT` 13. What is the difference between debounce and throttle? 14. How does the JavaScript Engine work? 15. What is the Event Loop and how does the Microtask Queue work? 16. Explain Virtual DOM and its comparison mechanism 17. How to control tab order in DOM (explain `tabIndex`) 18. What is Event Capturing and Bubbling 19. How to override `toString` on `String.prototype` 20. What is OAuth and how does it work? 21. How does SSO work? 22. What are REST API methods and their differences? 23. Principles of Functional Programming 24. What are microservices? 𝗥𝗲𝗮𝗰𝘁-𝗦𝗽𝗲𝗰𝗶𝗳𝗶𝗰 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻𝘀 1. Why do keys matter in React and how do they improve performance? 2. Explain how `useState` works internally 3. Implement a basic version of `useState` 4. What are React Portals? How are modals mounted using them? 5. What are Error Boundaries in React? 6. How does memoization work in React? 7. SSR vs CSR with examples and use-cases 8. What is Module Federation? 9. What is Micro-Frontend Architecture? 10. Server-Side Rendering techniques to improve SEO 11. What are memory leaks in React and how to detect them? 12. How to measure performance in a React application? 13. How would you build a tool like Create React App? 14. How do you structure reusable UI components in React? ........................................................................................................................................ Follow TheVinia Everywhere Stay connected with TheVinia and keep learning the latest in Web Development, React, and Tech Skills. 🎥 YouTube – Watch tutorials, roadmaps, and coding guides 👉 https://lnkd.in/gfKgVVFf 📸 Instagram – Get daily coding tips, updates, and learning content 👉 https://lnkd.in/gK4S-ah8 💼 Telegram – Follow our journey, insights, and professional updates 👉 https://lnkd.in/gU8M8hwd 💼 Medium : https://lnkd.in/gy9iSHqv ✨ Join our community and grow your tech skills with us.
To view or add a comment, sign in
-
React Learning Series | Contd... #Day20: React 19 Activity Component (Canary/Experimental) Tired of losing component state when using conditional rendering? Or killing performance by hiding elements with CSS? 🚀 React 19 introduces Activity Component It Offers: ✅ State Preservation: <Activity mode="hidden"> keeps your component in the background. If a user typed in an input or moved a slider, that data stays exactly where they left it. ✅ Low-Priority Background Updates: While a component is hidden, React still allows it to re-render in response to prop changes, but it does so at a lower priority. ✅ Instant Restorations: Because the DOM and state are preserved, switching back to visible feels nearly instant—no "loading" states or re-fetching data from scratch. ✅ Automatic Effect Cleanup: When hidden, React automatically calls cleanup functions for useEffect and useLayoutEffect. This stops active subscriptions, timers, or video/audio playback while the user isn't looking, but "resumes" them instantly when made visible again. Best Use Cases: 👉 Tabbed Interfaces: Switch between "Home" and "Settings" without losing the user’s progress or form data. 👉 Modals & Sidebars: Hide transient UI without resetting scroll positions or open dropdowns. 👉 Pre-rendering: Silently render a page the user is likely to visit next in a hidden state so it's ready the moment they click. 👉 Media Previews: Pause background video/audio when hidden while keeping the playback position exactly where the user left off. #ReactJS #WebDevelopment #Frontend #React19 #Javascript #ProgrammingTips #WebDev
To view or add a comment, sign in
-
Today I learned how form handling works in React using React Hook Form, which makes managing multiple input fields and validations super easy! 🔹 What is React Hook Form? React Hook Form is a library that simplifies form handling in React. Instead of manually managing state for every input, it lets React handle forms efficiently with minimal re-renders. 🔹 Managing Multiple Inputs All input fields can be registered using the register function, and validations can be added easily. Example idea: import { useForm } from "react-hook-form"; const { register, handleSubmit, formState: { errors } } = useForm(); <form onSubmit={handleSubmit(onSubmit)}> <input {...register("name", { required: "Name is required" })} /> {errors.name && <p>{errors.name.message}</p>} <input {...register("email", { required: "Email is required" })} /> {errors.email && <p>{errors.email.message}</p>} <input type="submit" /> </form> 🔹 Handling Validations & Errors register connects inputs to React Hook Form errors object shows validation errors Works well with external validation libraries like Yup 💡 Key Takeaway Using React Hook Form helps us: ✔ Reduce boilerplate and re-renders ✔ Manage multiple inputs efficiently ✔ Handle validations easily ✔ Build scalable and maintainable forms Special thanks to Devendra Dhote and Sheryians Coding School for the insights! 📌 Day 17 of my 21 Days React Learning Challenge #ReactJS #JavaScript #FrontendDevelopment #WebDevelopment #LearningInPublic #ReactForms
To view or add a comment, sign in
-
-
🚀 Callback Functions in JavaScript A callback function is a function that is passed as an argument to another function and is executed later, after some operation is completed. 👉 In simple words: “A function that runs after something else finishes.” 🔹 Example function greet(name, callback) { console.log("Hello " + name); callback(); } function sayBye() { console.log("Goodbye!"); } greet("Javascript", sayBye); Output: Hello Javascript Goodbye! >> sayBye is the callback function >> It is passed into greet >> It runs after greeting 🔹 Types of Callbacks 1) Synchronous Callback (runs immediately) [1, 2, 3].forEach(function(num) { console.log(num); }); 2) Asynchronous Callback (runs later) setTimeout(function() { console.log("Delayed execution"); }, 1000); 🔹 Why Are Callbacks Important? They are mainly used for: >>Handling asynchronous operations (like API calls, timers) >>Making functions more flexible and reusable >> Controlling execution order 🔹 Problems with Callbacks: >>>Callback Hell (Nested callbacks) getData(function(a) { getMoreData(a, function(b) { getMoreData(b, function(c) { console.log(c); }); }); }); >>> This becomes hard to read and maintain >>> This structure is also called “Pyramid of Doom” 🔹 Modern Solution To solve this, we use: >> Promises >> Async/Await 🔹 Key Points ✔️ Functions are first-class citizens in JavaScript ✔️ Callbacks allow async programming ✔️ Used heavily in APIs, events, timers ✔️ Can be synchronous or asynchronous #JavaScript #WebDevelopment #Frontend #Programming #Coding #AsyncJS #Developers #Learning #Tech
To view or add a comment, sign in
-
🚀 Day 16 of My #React Learning Journey – #State_vs_Props Today I learned the difference between State and Props, two core concepts that control how data flows in React applications. 🧠 State vs Props (Quick Comparison) 🔹 Purpose State → Manage internal component data Props → Pass data from parent to child 🔹 Mutability State → Mutable (can be updated) Props → Immutable (read-only) 🔹 Ownership State → Owned by the component Props → Owned by the parent component 🔹 Access State → [state, setState] using Hooks Props → props or destructured {name} 🔹 Re-render State → Component re-renders when state updates Props → Re-render only when props change 🧩 Example – Using Props & State Together import { useState } from "react"; function User(props) { const [age, setAge] = useState(props.initialAge); return ( <div> <h2>Name: {props.name}</h2> <h3>Age: {age}</h3> <button onClick={() => setAge(age + 1)}>Increase Age</button> </div> ); } // App.jsx function App() { return <User name="Sharath" initialAge={22} />; } export default App; 💡 Here, props provide initial data, and state manages dynamic updates. ⚡ Key Takeaway 👉 Props = Data passed from parent (read-only) 👉 State = Data managed inside component (changeable) Understanding this difference is essential for building dynamic and scalable React applications. Excited to continue my React journey! 💻✨ #React #JavaScript #FrontendDevelopment #WebDevelopment #ReactJS #State #Props #LearningJourney #10000 Coders
To view or add a comment, sign in
-
-
React Learning Series | Contd... #Day18: userEvent vs fireEvent (Stop Writing Unrealistic Tests) 🔺 While testing React apps using Jest + React Testing Library, choosing the right event utility matters more than you think. 👉 Two commonly used APIs: ✔️ fireEvent ✔️ userEvent Let’s understand with examples: Example 1: const input = screen.getByRole('textbox'); fireEvent.change(input, { target: { value: 'Hello' } }); 🔴 Problem: 👉 Directly mutates value 👉 Skips real user behavior 👉 No key events (keydown, keyup, etc.) This can lead to false-positive tests ❌ ====================================================== Example 2: const input = screen.getByRole('textbox'); await user.type(input, 'Hello'); ✅ Why this is better: 👉 Simulates real typing behavior 👉 Triggers full event sequence 👉 Handles async interactions naturally 🧠 Key Difference: fireEvent 👉 Low-level (manual event trigger) userEvent 👉 High-level (real user simulation) ✴️ When to use what? 🚀 Prefer userEvent for: 👉 typing 👉 clicking 👉 tab navigation 👉 accessibility testing 🚀 Use fireEvent only when: 👉 you need granular control 👉 simulating edge/rare DOM events #React #JavaScript #Frontend #Testing #Jest #RTL #WebDevelopment #CleanCode
To view or add a comment, sign in
-
Learning React can be overwhelming when you're not sure what to learn next. Many beginners jump between tutorials without a clear direction, which slows down their progress. To help solve this, I wrote a step-by-step React roadmap that breaks down the exact concepts developers should focus on to build strong frontend skills. The article covers: • Core React fundamentals • Important tools and concepts to master • A structured path for becoming job-ready If you're learning frontend development or planning to start with React, this roadmap can help you stay focused. Read the full article here: https://lnkd.in/diZDrM3G #React #FrontendDevelopment #WebDevelopment #JavaScript #Programming
To view or add a comment, sign in
-
Day 2 of learning React Today I explored one of the most important concepts in React State. State is simply data that is tied to your UI. When the state changes, React automatically updates the HTML (UI) to reflect the new data. This is what makes React powerful and dynamic. To manage state, we use useState(). Example: const [count, setCount] = useState(0); count - the current state (data) setCount - the function used to update that state A Bug I Encountered (and what I learned) While learning, I ran into an issue where I updated the state twice in the same function, but the second update overwrote the first. Example of the problem: setCount(count + 1); setCount(count + 1); You might expect the value to increase by 2, but it only increases by 1. Why? State updates in React are asynchronous they don’t happen immediately. React waits until all the code finishes running before applying updates. Solution (Using a variable or functional update) const newCount = count + 1; setCount(newCount); setCount(newCount + 1); New Concepts I Learned Lifting State Up (Definition): This is the process of moving state from a child component to a parent component so that multiple components can share and use the same data. Controlled Input (Definition): A controlled input is an input field whose value is controlled by React state. This means the input value is always in sync with the state. Example: const [value, setValue] = useState(''); <input value={value} onChange={(e) => setValue(e.target.value)} /> React is starting to make more sense now, especially how data flows and updates the UI. It’s not always easy, but each challenge is helping me understand things deeper. Looking forward to Day 3 💪 #React #JavaScript #FrontendDevelopment #WebDevelopment #LearningInPublic #CodingJourney #100DaysOfCode #BuildInPublic
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development