State Management in React with useReducer
When dealing with complex state logic in components, it can get quite messy when using useState
hook, so it’s not the best solution to use it in cases like these. useReducer
is a much better tool to deal with states in complex components, it is a structured and scalable approach.
What is useReducer
?
useReducer
is a React hook that helps you to deal with state management in React applications. Not only it is useful when handling complex state logic but also when the next state depends on the previous one. With useReducer
you can scale state logic cleanly and predictably.
How does useReducer Work?
useReducer
has concepts that are similar to the ones used in Redux, like reducers, so it’s quite easy for developers who have Redux experience to grasp the useReducer
. The hook uses four concepts that we need to understand: state
, dispatch
, reducer
, and initialState
, let's go through each of them, so it's easier to grasp it.
state
: it’s the state that changes based on the actions.dispatch
: a method that is used to trigger state changes.reducer
: a function that dictates how the state should change.initialState
: as the title suggests it’s a beginning state.
Now let's see all these concepts in action. Here is a basic example of a counter that increments or decrements based on user actions:
Performance Optimization
useReducer
pairs well with React.memo
to optimize performance, especially when you need to prevent unnecessary re-renders in components that receive complex objects from props.
Common Pitfalls
Even though useReducer
shines in scenarios where the state logic is complex, make sure not to overuse it in cases where useState
would be sufficient. Over-complication can lead to less maintainable code.
Subscribe to my newsletter
Read articles from Ugne Adomaityte directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by