React State useState vs useReducer

Lots of lines connecting smiley face nodes

Advantages of useState

  • Good for managing primitive state values in a component such string, integers or booleans
  • Simple and easy therefore it enables fast development as you can get up and running with it quickly
  • If two components need to share state you can “lift state up” to the closest common parent and pass down state through props. I’ve written another blog post exploring this here.

Advantages of useReducer

  • Good for managing more complicated states, such as objects with nested values
  • Useful for managing different actions on a state, often lots of useState declarations in one component could be combined into one useReducer function with different actions
  • Can pass a dispatch function through your components rather than using setState callbacks throughout your app which could lead to performance improvements

useState in-depth

<form onSubmit={onSubmit}>
<textarea
placeholder='Enter new note …'
name='listItem'
value={value}
onChange={(e) => setValue(e.target.value)}
/>
</form>
const [tasks, setTasks] = useState([]);const onSubmit = (e) => {
e.preventDefault();
if (value) {
setTasks([…tasks, value])
}
setValue('');
};

useReducer in-depth

function reducer(tasks, action) {
switch (action.type) {
case 'add':
return [action.payload.task, ...tasks]
default:
return tasks;
}
}
Simple notes application using useReducer

Conclusion

--

--

--

Writes about web development

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Journey with Docker and Node.js

Red Pill or Blue Pill | Matrix Algorithm

Hot reloading in React apps with code splitting

How to Inject HTML into React Using IFrame

Pass Data Between Pages React Native

When to use ES6 class-based React components vs. functional ES6 React components?

下载和观看 鬼灭之刃剧场版:无限列车篇 2020 (Demon Slayer: Kimetsu no Yaiba) 完整版本 HD/BluRay

Lossless Backpressure in RxJS

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Lizzie Hard

Lizzie Hard

Writes about web development

More from Medium

Core React concepts

Quiz App with React (Class components ) and Redux

React Hooks With Context

How to Create hello world react application?