开源日报每天推荐一个 GitHub 优质开源项目和一篇精选英文科技或编程文章原文,坚持阅读《开源日报》,保持每日学习的好习惯。

今日推荐开源项目:《WeChatMsg》
今日推荐英文原文:《5 React useState Mistakes That Can Put Your Job at Risk: Avoid These Pitfalls!》


开源项目

今日推荐开源项目:《WeChatMsg》传送门:项目链接

推荐理由:可以提取微信聊天记录,将其导出成HTML、Word、CSV文档永久保存,对聊天记录进行分析生成年度聊天报告,还挺有趣的


英文原文

今日推荐英文原文:《5 React useState Mistakes That Can Put Your Job at Risk: Avoid These Pitfalls!》

推荐理由:useState 5个实用方法,避免在工作中出现意想不到的错误


🚫⚠️ 5 React useState Mistakes That Can Put Your Job at Risk: Avoid These Pitfalls! 🔥💥

Hey, React developers! We all love the power and simplicity of the useState hook, but let’s face it, even the most experienced coders can make mistakes.

When it comes to managing state in React, a wrong move can cause bugs, performance issues, and even worse — put your job on the line.

In this article, we’ll unveil five common useState mistakes that you should avoid at all costs.

Stay tuned, learn from these pitfalls, and keep your React code in tip-top shape!

  1. Ignoring the Immutable Rule 🧱🚫:

React state is immutable, meaning you should never mutate it directly. One common mistake is accidentally modifying the state object instead of creating a new one.

Mutating the state can lead to unpredictable behavior and make it difficult to track changes.

Always use the setter function provided by useState to update the state and ensure immutability.

Remember, immutability is key to maintaining a stable and predictable state in your React components.

Example of a mistake:

// Incorrect: Mutating the state directly  
const [count, setCount] = useState(0);  

function increment() {  
  count += 1; // Avoid this!  
  setCount(count); // Will not trigger re-render  
}

Correct approach:

// Correct: Updating the state immutably  
const [count, setCount] = useState(0);  

function increment() {  
  setCount((prevCount) => prevCount + 1);  
}

2. Misunderstanding Asynchronous Updates ⏳😨:

React’s state updates may be asynchronous, which can lead to unexpected results when performing multiple updates in a row.

If you rely on the previous state when updating, using the setter function’s callback syntax is crucial to ensure accurate results.

Failing to account for the asynchronous nature of state updates can cause data inconsistencies and leave you scratching your head in confusion.

Example of a mistake:


// Incorrect: Not accounting for asynchronous updates  
const [count, setCount] = useState(0);  

function incrementTwice() {  
  setCount(count + 1);  
  setCount(count + 1);  
  console.log(count); // Outputs 0, not 2  
}

Correct approach:


// Correct: Using the callback syntax for accurate updates  
const [count, setCount] = useState(0);  

function incrementTwice() {  
  setCount((prevCount) => prevCount + 1);  
  setCount((prevCount) => prevCount + 1);  
  console.log(count); // Outputs 2  
}

3. Overusing State for Derived Values 🎯💡:

The useState hook is ideal for managing simple stateful values, but it’s not meant for calculating complex derived values.

Relying heavily on state for derived values can result in unnecessary re-renders and negatively impact performance.

Instead, leverage memoization techniques (such as useMemo or custom memoization functions) to compute and store derived values, reducing the computational load and optimizing your React components.

Example of a mistake:


// Incorrect: Using state for derived values  
const [count, setCount] = useState(0);  
const doubleCount = count * 2; // Derived value  

function handleClick() {  
  setCount(count + 1); // Unnecessary re-render of doubleCount  
}

Correct approach:


// Correct: Using memoization for derived values  
const [count, setCount] = useState(0);  

const doubleCount = useMemo(() => count * 2, [count]);  

function handleClick() {  
  setCount((prevCount) => prevCount + 1); // Only updates count, not doubleCount  
}

4. Neglecting to Group Related State Variables 👥📦:

As your React components grow, it’s easy to end up with a long list of individual useState hooks for each state variable.

However, this approach can make your code harder to manage and understand.

Instead, consider grouping related state variables into objects or custom data structures.

By organizing your state logically, you can improve code readability, reduce clutter, and make it easier to reason about your component’s state.

Example of a mistake:


// Incorrect: Individual useState hooks for each variable  
const [name, setName] = useState('');  
const [age, setAge] = useState(0);  
const [city, setCity] = useState('');  
// ... more individual state variables

Correct approach:


// Correct: Grouping related state variables  
const [user, setUser] = useState({  
  name: '',  
  age: 0,  
  city: '',  
  // ... more related properties  
});  

function handleInputChange(event) {  
  setUser((prevUser) => ({  
    ...prevUser,  
    [event.target.name]: event.target.value,  
  }));  
}

5. Violating the Single Source of Truth Principle 📚🔒:

In React, it’s important to follow the principle of having a single source of truth for your state.

When multiple useState hooks or state variables hold the same or related data, inconsistencies and synchronization issues can occur.

To avoid this mistake, consider centralizing your state management using more advanced state management libraries like Redux or Context API, ensuring a single source of truth and enabling better control and coordination of your app’s state.

Example of a mistake:


// Incorrect: Multiple useState hooks for related data  
const [firstName, setFirstName] = useState('');  
const [lastName, setLastName] = useState('');  
const [fullName, setFullName] = useState('');  

function handleInputChange(event) {  
  // Updating multiple state variables, risk of inconsistency  
  if (event.target.name === 'firstName') {  
    setFirstName(event.target.value);  
    setFullName(`${event.target.value} ${lastName}`);  
  } else if (event.target.name === 'lastName') {  
    setLastName(event.target.value);  
    setFullName(`${firstName} ${event.target.value}`);  
  }  
}

// Correct: Centralizing state management  
const [user, setUser] = useState({  
  firstName: '',  
  lastName: '',  
  fullName: '',  
});  

function handleInputChange(event) {  
  setUser((prevUser) => ({  
    ...prevUser,  
    [event.target.name]: event.target.value,  
    fullName: `${prevUser.firstName} ${prevUser.lastName}`,  
  }));  
}

Congratulations! By avoiding these common useState mistakes, you’re on your way to becoming a React pro.

Remember to respect immutability, handle asynchronous updates correctly, use state for its intended purpose, organize related state variables wisely, and follow the single source of truth principle.

With these tips, you’ll keep your React code clean, efficient, and free from career-threatening mistakes.

Happy coding and may your React apps flourish! 💪💻✨


下载开源日报APP:https://openingsource.org/2579/
加入我们:https://openingsource.org/about/join/
关注我们:https://openingsource.org/about/love/