惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

U
Unit 42
P
Proofpoint News Feed
The Last Watchdog
The Last Watchdog
S
Secure Thoughts
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
N
News | PayPal Newsroom
Application and Cybersecurity Blog
Application and Cybersecurity Blog
O
OpenAI News
S
Security @ Cisco Blogs
宝玉的分享
宝玉的分享
Hacker News: Ask HN
Hacker News: Ask HN
T
Troy Hunt's Blog
Google Online Security Blog
Google Online Security Blog
WordPress大学
WordPress大学
有赞技术团队
有赞技术团队
TaoSecurity Blog
TaoSecurity Blog
Help Net Security
Help Net Security
Latest news
Latest news
NISL@THU
NISL@THU
S
Security Affairs
博客园_首页
C
CXSECURITY Database RSS Feed - CXSecurity.com
博客园 - 聂微东
AI
AI
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Recent Announcements
Recent Announcements
P
Privacy & Cybersecurity Law Blog
小众软件
小众软件
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Hugging Face - Blog
Hugging Face - Blog
博客园 - 司徒正美
AWS News Blog
AWS News Blog
W
WeLiveSecurity
Google DeepMind News
Google DeepMind News
I
InfoQ
Schneier on Security
Schneier on Security
Recent Commits to openclaw:main
Recent Commits to openclaw:main
T
The Exploit Database - CXSecurity.com
IT之家
IT之家
T
Threatpost
Scott Helme
Scott Helme
L
LINUX DO - 热门话题
腾讯CDC
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
N
News and Events Feed by Topic
L
LINUX DO - 最新话题
F
Full Disclosure
大猫的无限游戏
大猫的无限游戏
H
Heimdal Security Blog
S
SegmentFault 最新的问题

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback()
3 Rules of React State Management
Dmitri Pavlutin · 2020-03-04 · via Dmitri Pavlutin Blog

State inside a React component is the encapsulated data that is persistent between renderings. useState() is the React hook responsible for managing state inside a functional component.

I like that useState() indeed makes the work with state quite easy. But often I encounter questions like:

  • should I divide my component's state into small states, or keep a compound one?
  • if the state management becomes complicated, should I extract it from the component? How to do that?
  • if useState() usage is so simple, when would you need useReducer()?

This post describes 3 easy rules that answer the above questions and help you design the component's state.

1. One concern

The first good rule of efficient state management is:

Make a state variable responsible for one concern.

Having a state variable responsible for one concern makes it conform to the Single Responsibility Principle.

Let's see an example of a compound state, i.e. a state that incorporates multiple state values.


const [state, setState] = useState({

on: true,

count: 0

});

state.on // => true

state.count // => 0


The state consists of a plain JavaScript object, having the properties on and count.

The first property, state.on, holds a boolean denoting a switch. The same way state.count holds a number denoting a counter, for example, how many times the user had clicked a button.

Then, let's say you'd like to increase the counter by 1:


// Updating compound state

setUser({

...state,

count: state.count + 1

});


You have to keep nearby the whole state to be able to update just count. This is a big construction to invoke to simply increase a counter: all because the state variable is responsible for 2 concerns: switch and counter.

The solution is to split the compound state into 2 atomic states on and count:


const [on, setOnOff] = useState(true);

const [count, setCount] = useState(0);


on state variable is solely responsible for storing the switch state. The same way count variable is solely responsible for a counter.

Now let's try to update the counter:


setCount(count + 1);

// or using a callback

setCount(count => count + 1);


count state, which is responsible for counting only, is easy to reason about, and respectively easy to update and read.

Don't worry about calling multiple useState() to create state variables for each concern.

Note, however, that if you have way too much useState() variables, there's a good chance that your component violates the Single Responsibility Principle. Just split such components into smaller ones.

Extract complex state logic into a custom hook.

Would it make sense to keep complex state operations within the component?

The answer is in fundamentals (as usually happens).

React hooks are created to isolate the component from complex state management and side effects. So, since the component should be concerned only about the elements to render and some event listeners to attach, the complex state logic should be extracted into a custom hook.

Let's consider a component that manages a list of products. The user can add new product names. The constraint is that product names have to be unique.

The first attempt is to keep the setter of product names list state directly inside the component:


function ProductsList() {

const [names, setNames] = useState([]);

const [newName, setNewName] = useState('');

const map = name => <div>{name}</div>;

const handleChange = event => setNewName(event.target.value);

const handleAdd = () => {

const s = new Set([...names, newName]);

setNames([...s]);

};

return (

<div className="products">

{names.map(map)}

<input type="text" onChange={handleChange} />

<button onClick={handleAdd}>Add</button>

</div>

);

}


names state variable holds the product names. When the Add button is clicked, handleAdd() event handler is invoked.

Inside handleAdd(), a Set object is used to keep the product names unique. Should the component be concerned about this implementation detail? Nope.

It would be better to isolate the complex state setter logic into a custom hook. Let's do that.

The new custom hook useUnique() takes care of keeping the items unique:


// useUnique.js

export function useUnique(initial) {

const [items, setItems] = useState(initial);

const add = newItem => {

const uniqueItems = [...new Set([...items, newItem])];

setItems(uniqueItems);

};

return [items, add];

};


Having the custom state management extracted into a hook, the ProductsList component becomes much lighter:


import { useUnique } from './useUnique';

function ProductsList() {

const [names, add] = useUnique([]);

const [newName, setNewName] = useState('');

const map = name => <div>{name}</div>;

const handleChange = event => setNewName(e.target.value);

const handleAdd = () => add(newName);

return (

<div className="products">

{names.map(map)}

<input type="text" onChange={handleChange} />

<button onClick={handleAdd}>Add</button>

</div>

);

}


const [names, addName] = useUnique([]) is what enables the custom hook. The component is no longer cluttered with complex state management.

If you'd like to add a new name to the list, you only have to invoke add('New Product Name').

Bottom line, the benefits of extracting the complex state management into a custom hook are:

  • The component becomes free of state management details
  • The custom hook can be reused
  • The custom hook can be easily tested in isolation

Extract multiple state operations into a reducer.

Continuing the example with ProductsList, let's introduce a Delete operation, which deletes a product name from the list.

Now you have to code 2 operations: adding and deleting products. The handle these operations, it makes sense to create a reducer and make the component free of state management logic.

Again, this approach fits the idea of hooks: extract the complex state management out of the components.

Here's a possible implementation of the reducer that adds and deletes products:


function uniqueReducer(state, action) {

switch (action.type) {

case 'add':

return [...new Set([...state, action.name])];

case 'delete':

return state.filter(name => name !== action.name);

default:

throw new Error();

}

}


Then uniqueReducer() can be used inside the products list by invoking React's useReducer() hook:


function ProductsList() {

const [names, dispatch] = useReducer(uniqueReducer, []);

const [newName, setNewName] = useState('');

const handleChange = event => setNewName(event.target.value);

const handleAdd = () => dispatch({ type: 'add', name: newName });

const map = name => {

const delete = () => dispatch({ type: 'delete', name });

return (

<div>

{name}

<button onClick={delete}>Delete</button>

</div>

);

}

return (

<div className="products">

{names.map(map)}

<input type="text" onChange={handleChange} />

<button onClick={handleAdd}>Add</button>

</div>

);

}


const [names, dispatch] = useReducer(uniqueReducer, []) enables uniqueReducer. names is the state variable holding the product names, and dispatch is a function to be called using an action object.

When Add button is clicked, the handler invokes dispatch({ type: 'add', name: newName }). Dispatching an add action makes the reducer uniqueReducer add a new product name to the state.

In the same way, when Delete button is clicked, the handler invokes dispatch({ type: 'delete', name }). Dispatching a remove action removes the product name from the state of names.

Interestingly, the reducer is a special case of Command design pattern.

4. Conclusion

A state variable should be responsible for one concern.

If the state has a complicated update logic, extract this logic out of the component into a custom hook.

Same way, if the state requires multiple operations, use a reducer to incorporate these operations.

No matter what rule you use, the state should be as simple and decoupled as possible. The component should not be cluttered with the details of how the state is updated: these should be a part of a custom hook or a reducer.

Conforming to these 3 rules will make your state logic easy to understand, maintain, and test.