Learned a React hook mistake and how to fix it

⚛️ A quick React learning story from my coding journey! While working on a small React project, I ran into a weird error when using the useState hook. I had declared it outside the component function — and React wasn’t happy about it! 😅 Here’s what I learned: ❌ Wrong way: const [count, setCount] = useState(0); // ❌ Outside the component function Counter() { return <button>{count}</button>; } ✅ Correct way: function Counter() { const [count, setCount] = useState(0); // ✅ Inside the component return <button onClick={() => setCount(count + 1)}>Count: {count}</button>; } 💡 Lesson learned: useState (and all React hooks) must be called inside the component function — not outside or inside loops or conditions. React uses the order of hooks to track state, and breaking that rule confuses it. It was a small mistake, but understanding why it happens really helped me grasp how hooks work behind the scenes. Every bug is just React teaching you something new. 💪✨ #ReactJS #JavaScript #MERNStack #FrontendDevelopment #WebDevelopment #LearningByDoing #CodingJourney

At first, I also made the same mistakes... 😅

Like
Reply

To view or add a comment, sign in

Explore content categories