How useState works in React: A deep dive

⚡𝗪𝗲 𝗮𝗹𝗹 𝘂𝘀𝗲 𝙪𝙨𝙚𝙎𝙩𝙖𝙩𝙚... 𝗯𝘂𝘁 𝗱𝗼 𝘆𝗼𝘂 𝗿𝗲𝗮𝗹𝗹𝘆 𝗸𝗻𝗼𝘄 𝘄𝗵𝗮𝘁 𝗵𝗮𝗽𝗽𝗲𝗻𝘀 𝘄𝗵𝗲𝗻 𝘆𝗼𝘂 𝗰𝗹𝗶𝗰𝗸 𝘁𝗵𝗮𝘁 𝗯𝘂𝘁𝘁𝗼𝗻? If you’ve ever built a form, a toggle, or even a theme switcher in React — chances are, 𝘂𝘀𝗲𝗦𝘁𝗮𝘁𝗲 was your first hook friend 💡 Let’s decode it — not just how to use it, but how it actually works behind the scenes. 💡 𝙒𝙝𝙖𝙩 𝙞𝙨 𝙪𝙨𝙚𝙎𝙩𝙖𝙩𝙚? useState is a special React Hook that lets you add state to functional components.Before hooks, only class components could manage state. Now with useState, every component can remember values and react to changes all without writing classes. 🧠 what happens in the example:  • 𝘠𝘰𝘶 𝘪𝘯𝘪𝘵𝘪𝘢𝘭𝘪𝘻𝘦 𝘴𝘵𝘢𝘵𝘦 → 𝘶𝘴𝘦𝘚𝘵𝘢𝘵𝘦(𝘧𝘢𝘭𝘴𝘦)  • 𝘙𝘦𝘢𝘤𝘵 𝘴𝘵𝘰𝘳𝘦𝘴 𝘵𝘩𝘪𝘴 𝘷𝘢𝘭𝘶𝘦 𝘪𝘯𝘵𝘦𝘳𝘯𝘢𝘭𝘭𝘺  • 𝘞𝘩𝘦𝘯 𝘺𝘰𝘶 𝘤𝘢𝘭𝘭 𝘴𝘦𝘵𝘐𝘴𝘋𝘢𝘳𝘬(!𝘪𝘴𝘋𝘢𝘳𝘬) → 𝘙𝘦𝘢𝘤𝘵 𝘶𝘱𝘥𝘢𝘵𝘦𝘴 𝘵𝘩𝘦 𝘴𝘵𝘢𝘵𝘦 𝘢𝘯𝘥  𝘳𝘦-𝘳𝘦𝘯𝘥𝘦𝘳𝘴 𝘵𝘩𝘦 𝘤𝘰𝘮𝘱𝘰𝘯𝘦𝘯𝘵  • 𝘛𝘩𝘦 𝘜𝘐 𝘯𝘰𝘸 𝘳𝘦𝘧𝘭𝘦𝘤𝘵𝘴 𝘵𝘩𝘦 𝘶𝘱𝘥𝘢𝘵𝘦𝘥 𝘵𝘩𝘦𝘮𝘦 𝘪𝘯𝘴𝘵𝘢𝘯𝘵𝘭𝘺 𝗧𝗵𝗮𝘁’𝘀 𝘁𝗵𝗲 𝗺𝗮𝗴𝗶𝗰 𝗼𝗳 𝗥𝗲𝗮𝗰𝘁’𝘀 𝗱𝗲𝗰𝗹𝗮𝗿𝗮𝘁𝗶𝘃𝗲 𝗻𝗮𝘁𝘂𝗿𝗲 ✨ 🧩 𝗖𝗼𝗺𝗺𝗼𝗻 𝗠𝗶𝘀𝘁𝗮𝗸𝗲𝘀 𝗗𝗲𝘃𝗲𝗹𝗼𝗽𝗲𝗿𝘀 𝗠𝗮𝗸𝗲 ❌ Trying to update state directly → isDark = true ✅ Always use the updater function → setIsDark(true) ❌ Expecting state to update instantly after calling setState ✅ React batches updates — so don’t log the value immediately after calling setIsDark. 𝘌𝘷𝘦𝘳𝘺 𝘵𝘪𝘮𝘦 𝘺𝘰𝘶𝘳 𝘤𝘰𝘮𝘱𝘰𝘯𝘦𝘯𝘵 𝘳𝘦𝘯𝘥𝘦𝘳𝘴, 𝘶𝘴𝘦𝘚𝘵𝘢𝘵𝘦 𝘨𝘪𝘷𝘦𝘴 𝘺𝘰𝘶 𝘵𝘩𝘦 𝘤𝘶𝘳𝘳𝘦𝘯𝘵 𝘴𝘵𝘢𝘵𝘦 𝘧𝘳𝘰𝘮 𝘙𝘦𝘢𝘤𝘵’𝘴 𝘪𝘯𝘵𝘦𝘳𝘯𝘢𝘭 𝘮𝘦𝘮𝘰𝘳𝘺. 𝘞𝘩𝘦𝘯 𝘴𝘦𝘵𝘚𝘵𝘢𝘵𝘦 𝘪𝘴 𝘤𝘢𝘭𝘭𝘦𝘥, 𝘙𝘦𝘢𝘤𝘵 𝘴𝘤𝘩𝘦𝘥𝘶𝘭𝘦𝘴 𝘢 𝘳𝘦-𝘳𝘦𝘯𝘥𝘦𝘳 𝘸𝘪𝘵𝘩 𝘵𝘩𝘦 𝘯𝘦𝘸 𝘷𝘢𝘭𝘶𝘦 — 𝘢𝘯𝘥 𝘶𝘱𝘥𝘢𝘵𝘦𝘴 𝘰𝘯𝘭𝘺 𝘸𝘩𝘢𝘵 𝘤𝘩𝘢𝘯𝘨𝘦𝘥. 𝗧𝗵𝗮𝘁’𝘀 𝗵𝗼𝘄 𝗥𝗲𝗮𝗰𝘁 𝘀𝘁𝗮𝘆𝘀 𝗳𝗮𝘀𝘁 ⚡ 💬 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻𝘀 𝘁𝗼 𝗣𝗿𝗮𝗰𝘁𝗶𝗰𝗲 1️⃣ What is the difference between initializing state directly vs through useState? 2️⃣ What happens internally when setState is called? 3️⃣ Why should we avoid updating state directly? 🔖 #ReactJS #ReactHooks #FrontendDeveloper #MERNStack #JavaScript #WebDevelopment #LearningSeries #LinkedInLearning #useState #ReactTips #JavaScript #ReactDeveloper #CodingJourney #InterviewPreparation #CareerGrowth #FrontendInterview #WebDevCommunity #DeveloperLife

  • text

To view or add a comment, sign in

Explore content categories