From the course: Master React 19 and Next.js 16 with Hands-On Projects and Real-World Applications

Unlock this course with a free trial

Join today to access over 25,200 courses taught by industry experts.

State reducer pattern

State reducer pattern

This session introduces the State Reducer pattern in React. You'll learn how to use a State Reducer function to control and modify state updates within a component, enabling powerful features like limiting updates, enforcing state constraints, and modifying updates before they're applied. This pattern offers a centralized and manageable way to handle complex state logic. Let's start with a simple React app. Let's create the Components folder inside src and add switch.jsx, a reusable toggle switch component. Moving to switch.jsx Let's create the Switch component. Let's import useState from React and initialize a state variable on with a boolean value of false. This variable will track whether the switch is on or off. I add a button element to the JSX. The button's text will dynamically display on if the on state is true and off otherwise. This lets the user see the current state of the switch. I am adding a Toggle function. Inside the Toggle function, I create a new variable, newOn, by…

Contents