How I Understood React State Updates One day I wrote this small React code: import { useState } from "react"; export default function App() { const [count, setCount] = useState(0); const handleClick = () => { setCount(count + 1); setCount(count + 1); setCount(count + 1); console.log(count); }; console.log(count); return ( <div> <h1>{count}</h1> <button onClick={handleClick}>Increment</button> </div> ); } And I thought something very simple would happen. I clicked the button and expected: 0 → 3 Because I increased the count three times. But React surprised me. The value became: 0 → 1 And I asked myself: 👉 Why didn't it increase to 3? So I stopped thinking like a JavaScript developer… and started thinking like React. What React actually sees React batches state updates. All three lines read the same old value. setCount(count + 1); setCount(count + 1); setCount(count + 1); • For React, this becomes: setCount(1) setCount(1) setCount(1) • So the final result is simply: 1 Not 3. • The correct way When the new state depends on the previous state, React gives us a better pattern: setCount(prev => prev + 1); setCount(prev => prev + 1); setCount(prev => prev + 1); Now React updates step by step. Result: 0 → 3 The lesson I learned State updates in React are not immediate. React schedules them and processes them together. So whenever state depends on the previous value, I now ask myself: 👉 Should I use the functional update? Small detail. Big difference. Still learning React the human way. 🚀 #JavaScript #FrontendDevelopment #LearningInPublic #CleanCode #ReactJS #useState #FrontendDevelopment #LearningInPublic #JavaScript #WebDevelopment #DeveloperJourney #ReactHook
React State Updates: Batching and Functional Updates Explained
More Relevant Posts
-
useEffect is the most abused hook in React. Here's what to use instead. I've reviewed hundreds of React codebases. useEffect is in the wrong place in about 60% of them. Not because developers are careless. Because nobody explained when NOT to use it. Here are the cases I see constantly — and what actually belongs there: // ❌ Case 1: Deriving state useEffect(() => { setFullName(`${firstName} ${lastName}`) }, [firstName, lastName]) // ✅ Just compute it const fullName = `${firstName} ${lastName}` No state. No effect. No re-render bug. // ❌ Case 2: Fetching data on mount (with App Router) useEffect(() => { fetch('/api/user').then(...) }, []) // ✅ Use a Server Component or TanStack Query // Data fetching is not a side effect in modern React // ❌ Case 3: Syncing two pieces of state useEffect(() => { if (selectedId) setDetails(getDetails(selectedId)) }, [selectedId]) // ✅ Derive during render const details = selectedId ? getDetails(selectedId) : null The React team has said explicitly: if you're using useEffect to sync state with other state, you probably have one piece of state too many. useEffect is for: → Connecting to external systems (WebSocket, third-party libraries, browser APIs) → Setting up subscriptions → Manual DOM manipulation That's mostly it. If you're using useEffect for anything that feels like when X changes, update Y, there's almost certainly a cleaner way. What's the strangest useEffect usage you've come across? #React #JavaScript #TypeScript #FrontendDevelopment #WebDevelopment
To view or add a comment, sign in
-
-
💡 Small React/Next.js Tip I Learned Today While working on a Next.js project, I needed to create a reusable configCreator utility. Example: const configCreator = () => ({ id: "id", label: "Option 1", icon: <Info size={12} /> }); Since I wanted to store it inside a utility file and reuse it across multiple places, I ran into an interesting problem. Because I was using a JSX component (<Info />) inside the util file, I had to change the file extension from .ts → .tsx. The issue was that this file already contained many other utility functions, so just to add one function using JSX, the whole file needed to become .tsx. The Better Approach I Found Instead of JSX, I used React.createElement. const configCreator = () => ({ id: "id", label: "Option 1", icon: React.createElement(Info, { size: 12 }) }); This allowed me to keep the file as .ts, since React.createElement doesn't require JSX. Why This Is Useful ✔ Keeps utility files clean and framework-agnostic ✔ Avoids unnecessary .tsx conversions ✔ Makes configs easier to reuse across the codebase Curious to hear from other React developers 👇 How would you tackle this in your React codebase? Keep it .tsx? Use React.createElement? Or structure the config differently? #React #NextJS #FrontendDevelopment #JavaScript #WebDevelopment
To view or add a comment, sign in
-
𝗚𝘂𝗶𝗱𝗲 #𝟭𝟲: 𝗧𝗵𝗲 𝟮𝟬𝟮𝟲 𝗙𝗿𝗼𝗻𝘁𝗲𝗻𝗱 𝗔𝗿𝗰𝗵𝗶𝘁𝗲𝗰𝘁𝘂𝗿𝗲 𝗗𝗶𝗹𝗲𝗺𝗺𝗮 — 𝗟𝗶𝘃𝗲𝘄𝗶𝗿𝗲 𝘃𝘀. 𝗜𝗻𝗲𝗿𝘁𝗶𝗮! Over our last 15 guides, we built a secure, highly scalable, and fully tested backend. But how do we connect all of this power to the user? Today, I explored the two "first-class citizens" of the Laravel frontend ecosystem: Livewire and Inertia.js. With the release of Laravel 12, we now have official starter kits for React, Vue, Svelte, and Livewire, complete with WorkOS AuthKit integration for instant passkeys and SSO. Here is how to choose your stack: 🏗️ 𝟭. 𝗜𝗻𝗲𝗿𝘁𝗶𝗮: 𝗧𝗵𝗲 𝗝𝗦𝗢𝗡 𝗕𝗿𝗶𝗱𝗴𝗲 Inertia is not a framework; it is a JSON protocol specification that acts as the glue between your backend and a modern frontend framework like React, Vue, or Svelte. Instead of returning HTML or building a complex REST/GraphQL API, your Laravel controllers simply return JavaScript components and their data. The Verdict: If your team already knows and loves modern JavaScript frameworks, Inertia gives you a true Single Page Application (SPA) experience without the tiresome complexity of client-side routing. ⚡ 𝟮. 𝗟𝗶𝘃𝗲𝘄𝗶𝗿𝗲: 𝗧𝗵𝗲 𝗕𝗮𝗰𝗸𝗲𝗻𝗱 𝗖𝗼𝗺𝗳𝗼𝗿𝘁 𝗭𝗼𝗻𝗲 Livewire takes an entirely different approach, allowing you to build dynamic, SPA-like interfaces without writing a single line of custom JavaScript. When a user interacts with a page, Livewire makes an asynchronous "API" call to the server, executes the PHP logic, and smartly re-renders only the parts of your Blade template that changed. The Verdict: If your team is primarily backend-oriented but refuses to compromise on user experience, Livewire is the perfect choice. 🔎 𝟯. 𝗧𝗵𝗲 𝗦𝗘𝗢 𝗙𝗮𝗰𝘁𝗼𝗿 𝗜𝗳 𝗦𝗲𝗮𝗿𝗰𝗵 𝗘𝗻𝗴𝗶𝗻𝗲 Optimization is a critical requirement for your application, Livewire holds a theoretical advantage because its views are rendered entirely on the server by default. While Inertia now supports Server-Side Rendering (SSR), setting it up requires running a separate Node.js server to render the page before returning it to the browser. Are you team React/Vue or team Livewire? Let me know which Laravel 12 starter kit you are spinning up next! 👇 #Laravel #Livewire #InertiaJS #WebDevelopment #SystemArchitecture #PHP #ReactJS #Guide16
To view or add a comment, sign in
-
-
💡 React Tip: Improving Form Performance in Large Applications While working on a complex React form with 50+ fields, I noticed frequent re-renders that were impacting performance and user experience. The solution? React Hook Form instead of traditional controlled inputs. Why React Hook Form works well for large forms: ✅ Minimal re-renders for better performance ✅ Lightweight and scalable for complex forms ✅ Built-in validation support ✅ Easy integration with validation libraries like Yup Example: const { register, handleSubmit } = useForm(); <input {...register("projectName")} /> Using this approach significantly improved form performance, maintainability, and scalability in our application. Curious to hear from other developers 👇 What tools or libraries do you prefer for handling large forms in React applications? #reactjs #frontenddevelopment #javascript #typescript #webdevelopment #reacthookform
To view or add a comment, sign in
-
From Vanilla JS to React (A Guide to Folders, Components, and JSX 💻): Transitioning from Vanilla JS to React is more than just learning a new syntax; it’s about understanding a new way to organize a project. After diving into the ecosystem, I’ve broken down the essential "DNA" of a modern React app. Here is what’s happening behind the scenes: 📂 The Anatomy of Folders assets/: The storage room for your images, SVGs, and brand icons. components/: The "Lego blocks" of your UI. Breaking the interface into reusable pieces like SearchBar.jsx or WeatherCard.jsx makes the code scalable and clean. ⚙️ The Core Files index.html: The only HTML file you'll ever need. It’s the "blank canvas" where React paints the UI. main.jsx: The bridge. This file "hydrates" your HTML by injecting the React app into the DOM. JSX (JavaScript XML): The superpower that lets us write HTML-like structures directly inside our logic. 🛡️ Project Housekeeping package.json: The manifest. It tracks your Dependencies (libraries like Tailwind CSS or Axios) so anyone can recreate your project with a single npm install. node_modules/: The heaviest folder you'll never touch. It holds the actual code for all your libraries. .gitignore: The gatekeeper. It ensures we don't upload thousands of library files or sensitive API keys to GitHub. Building in React is about thinking in systems. Every folder and file has a purpose in creating a fast, modular user experience. 💻✨ #ReactJS #WebDevelopment #Frontend #SoftwareEngineering #CodingJourney #Javascript #Vite
To view or add a comment, sign in
-
-
Day 21: useMemo vs useCallback (Most Confusing React Topic) Many React developers get confused between useMemo and useCallback. But the difference is actually simple 📌 What is useMemo? useMemo is used to memoize a computed value. 👉 It prevents expensive calculations from running again and again. import { useMemo, useState } from "react"; function App() { const [count, setCount] = useState(0); const expensiveValue = useMemo(() => { console.log("Calculating..."); return count * 10; }, [count]); return ( <div> <h1>{expensiveValue}</h1> <button onClick={() => setCount(count + 1)}>Increase</button> </div> ); } ✅ It stores the result/value. 📌 What is useCallback? useCallback is used to memoize a function. 👉 It prevents a function from being recreated on every render. import { useCallback, useState } from "react"; function App() { const [count, setCount] = useState(0); const handleClick = useCallback(() => { console.log("Clicked"); }, []); return ( <div> <button onClick={handleClick}>Click</button> <h1>{count}</h1> <button onClick={() => setCount(count + 1)}>Increase</button> </div> ); } ✅ It stores the function reference. 🔥 Simple Difference ✅ useMemo → returns a VALUE ✅ useCallback → returns a FUNCTION 📌 When to use them? useMemo ✔ Heavy calculations ✔ Derived data useCallback ✔ Passing functions as props ✔ React.memo optimized components 🎯 Interview Line 👉 useMemo memoizes values, useCallback memoizes functions. #ReactJS #useMemo #useCallback #FrontendDevelopment #JavaScript #WebDevelopment #CodingJourney #LearnInPublic
To view or add a comment, sign in
-
7 React Hooks You Must Master React Hooks replaced class components and changed how every React developer thinks about state, side effects, and performance. Master these 7 and you can handle 95 percent of React challenges. -> useState Your component's memory. Stores local state and triggers a re-render when it changes. The most used hook in React by a significant margin. -> useEffect Handles everything that happens outside the render cycle. API calls, subscriptions, timers, and DOM manipulation all live here. Runs after every render unless you control its dependency array. -> useContext Access global state without passing props through every level of the component tree. Works perfectly with the Context API for theme, auth, and shared configuration. -> useRef Two jobs: access DOM elements directly without a re-render, and store values that persist across renders without causing re-renders. More powerful than most developers realize when they first learn it. -> useMemo Memorizes the result of an expensive calculation. Only recalculates when its dependencies change. Use it when a computation is genuinely expensive and runs on every render. -> useCallback Memorizes a function reference between renders. When you pass a callback to a child component, useCallback prevents the child from re-rendering because it receives a new function reference every render. -> useReducer Complex state logic that involves multiple sub-values or state transitions that depend on the previous state. Think of it as a mini Redux built directly into React. More predictable than multiple useState calls for complex state. These seven hooks cover state management, side effects, performance optimization, and DOM interaction. Everything else in React builds on these foundations. Which of these seven do you use least and think you should probably use more? #React #ReactHooks #FrontendDevelopment #JavaScript #WebDevelopment #Developers
To view or add a comment, sign in
-
-
This video provides a comprehensive introduction to React, the powerful JavaScript library used to build dynamic and interactive user interfaces. Whether you are a beginner starting your web development journey or a developer looking to understand the shift from class-based to functional components, this guide covers everything you need to build efficient and maintainable applications. What You Will Learn: Core Concepts: Understand why React is component-driven and how it facilitates the creation of Single-Page Applications (SPAs) that feel "lightning-fast" because they don't require full page reloads. The Virtual DOM: Learn the "magic" behind React’s performance. We explain how React uses a lightweight sketch of your UI to compute differences and update only what's necessary in the real Browser DOM. JSX (JavaScript XML): Discover how to write HTML-like code directly within your JavaScript to define the structure of your UI. Functional vs. Class Components: Explore the foundational differences between the two. While Class Components were the traditional way to manage state, Functional Components are now the recommended standard thanks to the introduction of React Hooks. State & Props: Learn how to manage a component's "memory" with state and how to pass data dynamically between components using props. React Hooks: A deep dive into essential hooks like useState for data management and useEffect for handling side effects like data fetching and subscriptions. Conditional Rendering & Lists: Master techniques for showing/hiding elements and using the .map() method to render collections of data efficiently with unique keys. Environment Setup: Get up and running quickly by installing Node.js and using modern build tools like Vite for a faster development experience. Advanced Insights: We also touch on React Architecture, including best practices for directory structures, separate logic and design, and when to "lift state up" to share data between sibling components. Timestamps: 0:00 - Introduction to React & SPAs 2:15 - Virtual DOM Explained 5:00 - JSX Basics 8:30 - Functional vs. Class Components 12:45 - Props and State Management 18:20 - Mastering Hooks: useState & useEffect 25:10 - Rendering Lists and Keys 30:45 - Setup & Best Practices Links & Resources: Official React Quick Start Guide React Developer Roadmap Modern build tools: Vite
Demystifying React
https://www.youtube.com/
To view or add a comment, sign in
-
I struggled with this React concept more than I expected… 👇 👉 Why are my API calls running twice? ⚙️ What you’ll notice You open your network tab and suddenly see this: api/me → called twice api/roles → called twice api/permissions → called twice Just like in the screenshot 👇 Same request, duplicated… again and again. ⚙️ What’s actually happening In React (development mode), if your app is wrapped in Strict Mode, React will run effects twice on purpose. useEffect(() => { fetch("/api/users") .then(res => res.json()) .then(setUsers); }, []); Even though it looks like it should run once… it doesn’t (in dev). 🧠 What’s going on under the hood React basically does a quick cycle: mount → unmount → remount Why? To catch hidden side effects To check if cleanup is handled properly To make sure your logic doesn’t break on re-renders So if your API call runs twice, React is just making sure your code can handle it. 💡 The important part This only happens in development Production behaves normally (runs once) Your side effects should be safe to run multiple times 🚀 Final thought If your network tab looks “noisy” like the screenshot, it’s not React being broken — it’s React being careful. And once you understand this, debugging becomes a lot less confusing. #React #Frontend #JavaScript #WebDevelopment #ReactJS #SoftwareEngineering
To view or add a comment, sign in
-
𝐓𝐫𝐢𝐜𝐤𝐲 𝐑𝐞𝐚𝐜𝐭 𝐂𝐥𝐨𝐬𝐮𝐫𝐞 𝐈𝐧𝐭𝐞𝐫𝐯𝐢𝐞𝐰 𝐐𝐮𝐞𝐬𝐭𝐢𝐨𝐧 🤔 Many developers understand closures in JavaScript… but get confused when it comes to React. Question: What will be the output of this code? Example 👇 import React, { useState } from "react"; export default function App() { const [count, setCount] = useState(0); const handleClick = () => { setTimeout(() => { console.log(count); }, 1000); }; return ( <> Click </> ); } Now imagine: You click the button 3 times quickly and count updates each time What will be logged after 1 second? Answer 👇 It will log the SAME value multiple times ❌ Why? Because of closure. The setTimeout callback captures the value of count at the time handleClick was created. This is called a “stale closure”. Correct approach ✅ setTimeout(() => { setCount(prev => { console.log(prev); return prev; }); }, 1000); Or use useRef for latest value. Tip for Interview ⚠️ Closures + async code can lead to stale state bugs in React. Good developers know closures. Great developers know how closures behave in React. #ReactJS #JavaScript #Closures #FrontendDeveloper #WebDevelopment #ReactInterview #CodingInterview #ReactHooks
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
This is one of those concepts that feels tricky when you first encounter it. But the more you practice and apply it in real examples, the clearer it becomes. Thanks for sharing!