Let’s now learn React Hooks in this structured way

Let’s now learn React Hooks in this structured way
Category:Mern Stack
Tags:
JavaScriptJSMern StackNext.jsReact
Published:April 29, 2025

Share this post:

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
zkrana

Ziaul Kabir

Website Specialist

April 29, 2025

Comments (0)

No comments yet. Be the first to comment!