How React Remembers State Between Renders? When a component re-renders, the function runs again from top to bottom. So how does useState not reset every time? 🤔 function Counter() { const [count, setCount] = React.useState(0); return <button onClick={() => setCount(count + 1)}>{count}</button>; } Every render: The function runs again and Variables are recreated. So why doesn’t count go back to 0? What Actually Happens Internally React stores state outside the component function. Behind the scenes: 1) Each component has a Fiber node 2) React keeps a linked list of Hooks 3) It tracks Hooks based on call order State is not stored in your function. It’s stored in React’s internal Fiber system. The function is just a way for React to describe UI. Understanding this makes Hooks feel much less magical. #ReactJS #ReactInternals #ReactHooks #FrontendDevelopment #SoftwareEngineering #JavaScript
React State Persistence Explained
More Relevant Posts
-
Why is your useEffect sitting idle even after you've updated the variable? Look at this snippet. If you’re coming from a Vanilla JS background, count = count + 1 looks perfectly fine. But in React? This code is technically "dead." Why this won't work: * Mutation != Re-render: You are updating a local let variable. React has no "spy" watching your local variables. Unless you call a state setter (like setCount), React doesn't know it needs to re-render the component. * The Lifecycle Gap: useEffect only checks its dependency array ([count]) when the component re-renders. Since the button click doesn't trigger a render, React thinks nothing has changed. * The "Reset" Trap: Even if the component did re-render for some other reason, the first line let count = 0; would run again, resetting your value back to zero every single time. The Fix? Stop treating React like a standard script. Use useState. When you use const [count, setCount] = useState(0), you’re telling React: "Hey, keep an eye on this value. If I change it via setCount, please refresh the UI and check my Effects." Pro-tip: In React, if you want the UI to "react," you have to use the Hook. Simple as that. #ReactJS #WebDevelopment #Frontend #CodingTips #IndiaDevs #Javascript
To view or add a comment, sign in
-
-
𝗔 𝗦𝘂𝗯𝘁𝗹𝗲 𝗥𝗲𝗮𝗰𝘁 𝗕𝘂𝗴 𝗖𝗮𝘂𝘀𝗲𝗱 𝗯𝘆 𝗦𝘁𝗮𝗹𝗲 𝗦𝘁𝗮𝘁𝗲 Sometimes a bug in React isn’t caused by React itself. It comes from how JavaScript closures work. When you schedule a state update inside an asynchronous callback (like a timeout), that callback captures the value of state from the moment it was created. If the state changes before the callback runs, the update may still use the old value. This can lead to confusing behavior where your UI doesn’t update the way you expect. A safer approach is to use the functional update pattern. Instead of relying on the current state value, React gives you the latest state inside the updater function. This ensures your update always works with the most recent value. 👇 Example comparison below Day 13/100 — sharing practical frontend engineering lessons. Have you ever faced a bug caused by stale state in React? #ReactJS #FrontendEngineering #JavaScript #WebDevelopment #SoftwareEngineering
To view or add a comment, sign in
-
-
Monday – React Tip 💙 A React mistake that silently causes unnecessary re-renders. Passing objects directly as props. Example: const filters = { status: “active” } <Component filters={filters} /> Looks fine, right? But if this object is created inside the component, React sees a new reference on every render. That means even memoized components can re-render. Better pattern: Use useMemo for stable references when needed. const filters = useMemo(() => ({ status: “active” }), []) Why this matters: React compares references, not values. Small patterns like this make a huge difference in large applications. Advanced React isn’t about more hooks. It’s about controlling rendering behavior. See you tomorrow for JavaScript Concept Tuesday 👀 #ReactJS #FrontendDevelopment #WebPerformance #LearningInPublic
To view or add a comment, sign in
-
Ever wondered why changing one small thing in React doesn’t re-render the entire UI? 🤔 That’s reconciliation. In React, every update creates a new virtual DOM. But instead of updating everything, React compares the new tree with the previous one - and updates only what changed. Sounds simple, but small mistakes can break performance. 😬 • Missing or unstable keys ➡️ unnecessary re-renders • Recreating objects/functions ➡️ diffing becomes expensive • Large component trees ➡️ slower updates React is fast. But only if we help it. Reconciliation is not magic - it’s an optimization strategy based on assumptions. Understanding it changes how you structure components. 😉 Have you ever fixed a performance issue just by adding proper keys or memoization? #reactjs #frontend #webperformance #javascript #learninginpublic
To view or add a comment, sign in
-
-
Why does React say: "Don't call hooks conditionally"? 🤔 Let’s break it down simply. React doesn’t track hooks by name. It tracks them by order. Every render, React just walks through hooks like this: 1st hook → 2nd hook → 3rd hook That’s it. No labels. No IDs. Just position. Now imagine this 👇 if (condition) { useEffect(() => { // do something }); } 👉 First render: Hook1 → Hook2 → Hook3 👉 Next render (condition = false): Hook1 → Hook3 Now React gets confused 😵 It expects Hook2… but suddenly sees Hook3. This breaks the internal hook mapping — and boom 💥 unexpected bugs or crashes. 👉 The rule exists because hooks must run in the same order on every render. That’s why: ❌ No hooks inside conditions ❌ No hooks inside loops ❌ No hooks inside nested functions 👉 Always call hooks at the top level. Once you understand this, React hooks feel much less “magical” and more predictable. #ReactJS #JavaScript #FrontendDevelopment #WebDevelopment #LearnInPublic
To view or add a comment, sign in
-
Misunderstanding how JavaScript handles functions can hurt your UI performance. In JavaScript, functions are compared by reference. And in React, every render creates new function instances. So even if a function looks exactly the same, it’s actually a different reference in memory. That means when you pass a function as a prop, React sees it as a new value on every render. And if that component is wrapped with React.memo, it will still re-render. Not because React.memo doesn’t work, but because the prop actually changed. This can be solved by keeping the same function reference between renders, which is exactly what useCallback helps you do. This doesn’t mean you should use useCallback everywhere. It only matters when you need a stable function reference, like when passing props to memoized components. I’ve been using these techniques for a while, but it took me some time to really understand why they are often used together. This is a good example of how understanding the fundamentals of JavaScript can directly impact performance and behavior in React applications. (Simplified example in the image) #React #JavaScript #Frontend #WebDevelopment #SoftwareEngineering
To view or add a comment, sign in
-
-
Classic: Why is my ellipsis broken? It’s always funny watching a complex layout crumble because of a single line of CSS. You throw text-overflow: ellipsis at an element, but it just keeps pushing its neighbors around like it owns the place. The "Why": In Flexbox and Grid, items have min-width: auto by default. Your content is literally "too strong" for the container—it refuses to shrink smaller than the text itself. Until you give it permission to "slim down," that ellipsis isn't doing anything. The Irony: We build enterprise-grade apps with React and TypeScript, yet 50% of "broken" layouts are fixed by zeroing out a single property. If your 1fr column is acting up, you know what to do. #css #frontend #webdev #typescript #javascript #react #ui
To view or add a comment, sign in
-
-
Most React performance advice is wrong. Not because the patterns are bad but because developers apply them without understanding what React is actually doing. Here’s what I’ve learned: React.memo without useCallback is just theater. memo tells React: “Only re-render if prop references change.” But if you pass a new function reference on every render, memo does absolutely nothing. // ❌ Kills memo on every render <ProductCard onSelect={(id) => handleSelect(id)} /> // ✅ Actually works const handleSelect = useCallback((id) => { dispatch({ type: "SELECT", payload: id }); }, [dispatch]); useMemo has a cost use it surgically. React still performs dependency comparison on every render. For cheap computations, the memoization overhead can be higher than simply recalculating. Use useMemo only when: the computation is genuinely expensive the result is passed to a memoized child you’ve measured it, not assumed it Before reaching for memo or useMemo, ask: What is actually triggering the re-render? Can you eliminate the trigger instead of memoizing around it? Structural state changes beat memoization every time. What’s the nastiest React performance bug you’ve hit in production? #React #ReactJS #Frontend #TypeScript #WebDevelopment #MERN #JavaScript #SoftwareEngineering
To view or add a comment, sign in
-
Today while building a pagination component in React, I came across the use of Array.from() in JavaScript. The problem I was facing was simple: I wanted to show page numbers between the Previous and Next buttons. For example: Prev 1 2 3 4 5 Next At first, I was thinking about how to generate those numbers dynamically instead of writing them manually. That’s when I came across Array.from(). It helped me create an array of a specific length and then generate page numbers from it. Something like this: Array.from({ length: totalPages }, (_, i) => i + 1) This creates: [1, 2, 3, 4, 5] Which can then be mapped easily to render pagination buttons in React. A small thing, but it made pagination logic feel much cleaner and more dynamic. Am I understanding this correctly? Would love to know if there’s a better or more practical way you usually handle pagination numbers. #JavaScript #ReactJS #WebDevelopment #Frontend #Pagination
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development
Great explanation. This is also why the rules of hooks exist - since React tracks hooks by call order in the linked list, calling them conditionally would break the index mapping. Once you internalize the Fiber architecture, patterns like custom hooks and useReducer make much more sense.