Understanding when to use useState and useReducer in React

Adetoyese Kola-Balogun
2 min readJun 30, 2022
Photo by Lautaro Andreani on Unsplash

useState()

A functional component can be updated and modified using the useState hook. The hook returns a state variable and a method to update it after taking a single argument that represents the state’s initial value.

const [state, setState] = React.useState(initialState);

useReducer()

In the React Hooks API, there is a method called useReducer() that is similar to useState but provides you more flexibility over how the state is managed. It returns the state and dispatch method after receiving a starting state and a reducer function as parameters. Complex state logic in React applications can be managed with the aid of useReducer. UseReducer is a viable alternative to Redux, when paired with other Hooks like useContext. It may be clearly preferable in some circumstances.

const [state, dispatch] = React.useReducer(reducerFn, initialState, initFn);

When should you use useReducer()?

As was already mentioned, the useReducer hook handles more intricate state update logic. It is therefore apparent to use the useState hook if your state consists of a single boolean, number, or string. UseReducer, on the other hand, will be more suited if your state is a complex object (for instance, a deep object or array containing student bio data, grades and score).

Conclusion

UseReducer() is a substitute for useState() that offers additional control over state management and may facilitate testing. Use the way that you are familiar with and that is simpler for you and your coworkers to grasp. The useState() function can be used to handle all cases.

--

--

Adetoyese Kola-Balogun
0 Followers

Software Developer | React Expert | Building financial software solutions.