flâneur — a map of the web's best reading

Extracting State Logic into a Reducer – React

react.dev · 3,594 words · saved by 1 readers

Components with many state updates spread across many event handlers can get overwhelming. For these cases, you can consolidate all the state update logic outside your component in a single function, called a reducer. As your components grow in complexity, it can get harder to see at a glance all the different ways in which a component’s state gets updated. For example, the TaskApp component below holds an array of tasks in state and uses three different event handlers to add, remove, and edit tasks: Each of its event handlers calls setTasks in order to update the state. As this component grows, so does the amount of state logic sprinkled throughout it. To reduce this complexity and keep all your logic in one easy-to-access place, you can move that state logic into a single function outside your component, called a “reducer”. Reducers are a different way to handle state. You can migrate from useState to useReducer in three steps: Your event handlers currently specify what to do by sett

Learn React Managing State Copy page Copy Extracting State Logic into a Reducer Components with many state updates spread across many event handlers can get overwhelming. For these cases, you can consolidate all the state update logic outside your component in a single function, called a reducer. You will learn What a reducer function is How to refactor useState to useReducer When to use a reducer How to write one well Consolidate state logic with a reducer As your components grow in complexity, it can get harder to see at a glance all the different ways in which a component’s state gets updat

Explore this link on the map →

related reading