Profile img

Shahar Amir

@shaharamir@hackers.pub · 1 following · 2 followers

Love coding

React - useCallback & useMemo Misuse

Shahar Amir @shaharamir@hackers.pub

The `useCallback` and `useMemo` hooks in React are designed to optimize performance by memoizing functions and values, but using them indiscriminately can lead to unnecessary overhead. These hooks are beneficial when dealing with expensive calculations or when passing stable references to deeply nested child components. However, for simple operations like basic arithmetic or simple function declarations, the memoization provided by these hooks adds complexity without any performance gain. Overusing `useMemo` and `useCallback` introduces extra CPU cycles and can confuse developers, making the code harder to maintain. It's more efficient to apply these hooks selectively, focusing only on the parts of your application where they provide a tangible benefit, ensuring that React remains fast and your code stays clean.

Read more →
5

React is Simple!

Think React state is easy? One wrong move and your counter breaks.

Why It Happens

React batches state updates.
Using setState(state + 1) can overwrite updates with stale values.
The functional form setState(prev => prev + 1) ensures correctness.

Don't

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

setCount(count + 1);
setCount(count + 1); 
// ❌ Result: count = 1

Do

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

setCount(prev => prev + 1);
setCount(prev => prev + 1);
// ✅ Result: count = 2

Explanation

  • setCount(count + 1) → uses an old snapshot of state.
  • setCount(prev => prev + 1) → React passes the freshest value.

Updating state without prev is like asking for “one more slice” 🍕…
but the box already got emptied. Always ask from the current box.

4