Mern Stack

Let's now learn React Hooks in this structured way

Ziaul Kabir
••1 min read
Let's now learn React Hooks in this structured way

Great! Let’s now learn React Hooks in this structured way — one at a time — with:

  1. ✅ Core concept
  2. 📝 Detailed example (with realistic context)
  3. 🛠 Best practices
  4. ⚠️ Pitfalls to avoid
  5. 📤 Execution order (in lifecycle)
  6. 🧪 Optional CodeSandbox or timeline example if you want

🔹 Hook #1 — useState

✅ 1. Concept

useState is used to add local state to functional components.

State = data that can change over time (e.g., a count, a form input).

const [value, setValue] = useState(initialValue);
  
  • value: current state
  • setValue: function to update state

📝 2. Example: A Counter App

import React, { useState } from 'react';

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

  const increase = () => setCount(prev => prev + 1);
  const decrease = () => setCount(prev => prev - 1);
  const reset = () => setCount(0);

  return (
    <div>
      <h2>Counter: {count}</h2>
      <button onClick={increase}>+</button>
      <button onClick={decrease}>-</button>
      <button onClick={reset}>Reset</button>
    </div>
  );
}
  

This component:

  • Initializes count to 0
  • Updates it using setCount
  • React re-renders when count changes

🛠 3. Best Practices

  • ✅ Use one state per concept. Don’t jam everything into one object.
  • ✅ When new state depends on old: setState(prev => ...)
  • ✅ Initial value can be calculated lazily:
const [items, setItems] = useState(() => fetchInitialItems());
  

⚠️ 4. Common Pitfalls

  • ❌ Don’t update state directly:
// Wrong
count++;
setCount(count); // buggy
  
  • ✅ Instead, always use setCount(prev => prev + 1)
  • ❌ Avoid asynchronous confusion:
// This won't reflect updated count immediately
console.log(count); // still old
  

📤 5. Execution Order

Step Phase What Happens
1 Render useState(0) gives [0, setCount]
2 Click setCount(1) triggers re-render
3 Re-render count = 1
4 DOM updates React shows Counter: 1

Written by

Ziaul Kabir

Share:

Comments (0)

No comments yet. Be the first to comment!