🧠 What Actually Triggers a Re-render in React? Many developers memorize hooks. But fewer understand what really causes a component to re-render. Let’s break it down 👇 Example Code : function App() { const [count, setCount] = useState(0); const memoValue = useMemo(() => { console.log("useMemo runs"); return count * 2; }, [count]); useEffect(() => { console.log("useEffect runs"); }, [count]); return ( <button onClick={() => setCount(count + 1)}> {count} </button> ); } 🔄 What Happens When You Click? 1️⃣ State updates setCount triggers a re-render. 2️⃣ Component re-runs Entire function runs again. 3️⃣ useMemo runs (if dependency changed) 4️⃣ DOM updates 5️⃣ useEffect runs (after render) 🎯 Final Order Render → useMemo → Paint → useEffect 🧠 Important Notes React re-renders when state or props change useMemo runs during render useEffect runs after render useCallback does NOT run — it only stores a function Understanding execution order is what separates React users from React engineers. #ReactJS #FrontendDevelopment #JavaScript #ReactHooks #WebDevelopment #LearningInPublic
React Re-render Triggers: State, Props, and Hooks
More Relevant Posts
-
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
-
-
Today I learned about the useRef hook and how it helps us access DOM elements and persist values without re-rendering. 🔹 What is useRef? useRef is a React Hook that returns a mutable object with a .current property. It is mainly used for: • Accessing DOM elements • Storing values without causing re-render • Keeping previous values 🔹 Accessing DOM Elements We can directly access an element using useRef. import { useRef } from "react"; function App(){ const inputRef = useRef(); const focusInput = () => { inputRef.current.focus(); }; return ( <> <input ref={inputRef} /> <button onClick={focusInput}>Focus</button> </> ); } Here React gives direct access to the input element. 🔹 Storing Values Without Re-render Unlike state, updating useRef does NOT re-render the component. const countRef = useRef(0); countRef.current++; This is useful when we want to store values without updating UI. 🔹 useRef vs useState • useState → causes re-render • useRef → does NOT cause re-render 💡 Key Takeaway useRef is useful when: ✔ You need direct access to DOM ✔ You want to store values without re-render ✔ You want better performance in some cases 📌 Day 16 of my 21 Days JavaScript / React Learning Challenge #ReactJS #JavaScript #ReactHooks #FrontendDevelopment #LearningInPublic
To view or add a comment, sign in
-
-
🚨 React vs Vanilla JavaScript: the showdown that could save you weeks of work A: React – a component library that handles UI state, routing and ecosystem tools. It shines for large SPAs, offers reusable pieces and has a massive community. B: Vanilla JavaScript – pure browser language, no extra libraries, runs everywhere and lets you keep payload tiny. My verdict: Vanilla JavaScript wins for most client sites. In the past nine years I’ve built dozens of marketing pages, e‑commerce fronts and dashboards. When the page needs a simple form, a carousel or a dynamic headline, a few lines of native code load instantly and avoid the bundle size of a React build. I only reach for React when the product truly behaves like a single page app with complex state, multiple views and a dedicated development team. ✅ Your turn. A or B? Drop it in the comments. 💡 Check if your next project is overengineered. #ThisOrThat #WebDevelopment #WebDesign #Poll #TechDebate #Developer #JavaScript #ReactJS #Frontend #Coding #Performance #UX #WebPerformance #NoCode #Programming
To view or add a comment, sign in
-
🚀 Day 14/100: #100DaysOfCode Today was all about understanding the "Why" and "How" behind ReactJS, Next.js, and how they compare to other industry leaders like Vue.js. As I progress through my #100DaysOfCode, I’m realizing that choosing the right tool is just as important as writing the code itself. Here’s a breakdown of what I covered today: 1. What is ReactJS? React is a declarative, component-based JavaScript library for building UIs. It’s fast, flexible, and maintained by Meta (Facebook). The Magic of the Virtual DOM: Instead of refreshing the entire page, React uses a "Virtual DOM" to compare changes and only update the specific elements that actually changed. This is why React apps feel so snappy! 2. ReactJS vs. Next.js: Library vs. Framework ReactJS is a library focused on the View layer. It gives you freedom but requires you to pick your own tools for routing and state management. Next.js is a full-stack framework built on top of React. It comes with "batteries included"—built-in routing, Server-Side Rendering (SSR), and Static Site Generation (SSG) for better SEO and performance. 3. The Landscape: React vs. Next vs. Vue I spent some time comparing these three at a glance: Data Binding: React and Next use one-way data flow (predictable), while Vue supports two-way data binding (faster for simple forms). Scalability: While React is highly flexible, Next.js provides a more structured architecture for complex, large-scale applications. Why choose React? Pros: Simple design (JSX), massive community support, and total freedom to tailor tech stack. Cons: It’s not a full-scale framework out of the box, meaning you’ll need 3rd-party libraries for routing and validation. #100DaysOfCode #ReactJS #NextJS #VueJS #WebDevelopment #Programming #JavaScript #SoftwareEngineering #MERN
To view or add a comment, sign in
-
🔍 Understanding React Strict Mode’s Double Invocation in Development 🔍 If you’ve worked with React, you might have noticed some surprising behavior when using Strict Mode — certain functions get called twice. Why does this happen? And which parts of your component code are affected? Let’s clear this up! What’s getting called twice? Function component bodies Initializers for hooks like useState, useMemo, and useReducer Class component lifecycle methods: render(), shouldComponentUpdate(), getDerivedStateFromProps() What does NOT get called twice? useEffect and useLayoutEffect callbacks are not double-invoked. (Though React 18 does run these effects with a mount → unmount → mount cycle in Strict Mode for additional cleanup checks.) Why does React do this? React Strict Mode intentionally double-invokes these functions only in development to help you spot accidental side effects or impure code during render. This is crucial because: ✅ It ensures your render logic and hook initializers are pure and idempotent. ✅ It helps prevent subtle bugs that might show up only under certain conditions. ✅ It improves the robustness and predictability of your React apps. ⚠️ Remember: This double invocation happens only in development, and your production build remains unaffected. If you ever wondered why your components and hooks seem to “run” twice when Strict Mode is on — now you know it’s by design, helping you write better React code! 🚀 #ReactJS #ReactStrictMode #WebDevelopment #FrontendTips #JavaScript #CodingBestPractices
To view or add a comment, sign in
-
React is fast by default. But are YOU using it fast? Most React apps don't have a performance problem. They have a developer habit problem. Here are the advanced optimizations that separate senior devs from the rest: 1- Stop Abusing useEffect. Not everything belongs in a useEffect. Derived state? Compute it inline. Event-driven logic? Use handlers. useEffect is for synchronization, not control flow. 2- useMemo and useCallback. But only where it hurts. Wrapping everything in useMemo is not optimization, it's anxiety. Profile first. Memoize only when: A child component is wrapped in React.memo The value feeds a heavy computation It's a dependency in another hook 3- Code Splitting is Non-Negotiable Every route you don't lazy-load is bundle weight your user pays for. constDashboard=React.lazy(()=>import('./Dashboard')) Pair with <Suspense> and ship leaner initial loads. 4- Virtualize Long Lists Rendering 1,000 DOM nodes to show 10? That's a you problem. react-window or @tanstack/virtual renders only what's visible. Your scroll performance will thank you. 5- Avoid Anonymous Functions in JSX // ❌ New function reference on every render <Button onClick={()=>handleClick(id)}/> // ✅ Stable referenceconst handleItemClick =useCallback(()=>handleClick(id),[id]) React doesn't slow down. Unthoughtful patterns do. #React #Frontend #JavaScript #WebDevelopment #MERN #ReactJS #SoftwareEngineering #FrontendDevelopment
To view or add a comment, sign in
-
What Runs First in React? Most React developers know what useEffect, useMemo, and useCallback do individually. Far fewer know the exact order they execute in. And that gap causes bugs that are surprisingly difficult to trace. Here is the definitive execution order on first mount: -> Step 1: Rendering JSX React runs the function body of your component first. JSX is evaluated. console.log inside the return runs here. This is the render phase. -> Step 2: useMemo runs during render useMemo executes synchronously during the render phase, not after it. If you have an expensive computation wrapped in useMemo, it runs as part of building the component output. This is why useMemo can be used to compute values that are needed in the JSX itself. -> Step 3: useEffect runs after render After the component has rendered and the DOM has been updated, useEffect fires. It is intentionally deferred. This is where API calls, subscriptions, and side effects belong because they should not block the render. -> useCallback is different from all of them useCallback does not run during mounting. It stores a function reference. That function only executes when it is explicitly called. In the example on the right, increment only logs when you actually call increment(). The final order: Rendering JSX, then useMemo, then useEffect. Why this matters in practice: If you expect useEffect to run before useMemo, your state update will not be available when useMemo computes. If you expect useCallback to run automatically, your side effect will never fire. Getting the order wrong means working with stale data and writing code that behaves differently than you intended. Understanding execution order is not academic. It is the difference between components that behave predictably and ones that produce subtle timing bugs you spend hours debugging. Did you know the exact execution order before seeing this or did it surprise you? #React #ReactHooks #FrontendDevelopment #JavaScript #WebDevelopment #Developers
To view or add a comment, sign in
-
-
🔄 Understanding useReducer in React When managing state in React, most developers start with useState. But as applications grow, state logic can become complex. That’s where useReducer becomes very useful. Think of useReducer as a more structured way to manage state, especially when multiple state changes depend on specific actions. 📌 What is useReducer? useReducer is a React Hook that lets you manage state using a reducer function. It works similarly to how reducers work in Redux. It takes two main things: 1️⃣ A reducer function 2️⃣ An initial state const [state, dispatch] = useReducer(reducer, initialState); state → the current state dispatch → a function used to send actions reducer → decides how state should change 📌 Example const initialState = { count: 0 }; function reducer(state, action) { switch (action.type) { case "increment": return { count: state.count + 1 }; case "decrement": return { count: state.count - 1 }; default: throw new Error("Unknown action"); } } function Counter() { const [state, dispatch] = useReducer(reducer, initialState); return ( <> <p>{state.count}</p> <button onClick={() => dispatch({ type: "increment" })}> Increment </button> <button onClick={() => dispatch({ type: "decrement" })}> Decrement </button> </> ); } Here, instead of directly updating state like setCount, we dispatch actions and the reducer decides how the state should change. 📌 When Should You Use useReducer? ✅ When state logic is complex ✅ When multiple state updates depend on each other ✅ When managing objects or multiple state values ✅ When you want predictable state transitions 💡 Key Insight useReducer separates state logic from UI logic, making your components easier to read, test, and maintain. As React applications grow, this pattern helps keep your state management clean and scalable. 💬 Are you using **useState or useReducer more often in your React projects? #React #FrontendDevelopment #JavaScript #WebDevelopment #ReactHooks #LearningInPublic
To view or add a comment, sign in
-
-
Most people think React is just a JavaScript library. But that’s not why React became the most popular frontend technology in the world. React changed how developers think about building interfaces. Before React: UI development looked like this 👇 • Manual DOM updates • Complex UI logic • Hard-to-maintain code • Slow development cycles Then React introduced something powerful: Component-based architecture. Now developers can build apps like LEGO blocks. Small reusable pieces: 🔹 Navbar 🔹 Buttons 🔹 Cards 🔹 Forms 🔹 Dashboards Each component manages its own logic and state. This leads to: ⚡ Faster development ⚡ Cleaner code ⚡ Reusable UI ⚡ Better scalability But the real magic of React is the Virtual DOM. Instead of updating the whole page, React updates only the parts that change. Result? 🚀 Faster applications 🚀 Better user experience 🚀 High performance UI That’s why companies like Meta, Netflix, Airbnb, and Uber rely heavily on React. And with tools like: • Next.js • Redux Toolkit • Tailwind CSS • React Query React has become a complete ecosystem for modern web apps. The question is no longer: "Should you learn React?" The real question is: How well can you master it? What’s your favorite thing about React? 👇 #React #WebDevelopment #JavaScript #Frontend #FullStack #Programming #Tech
To view or add a comment, sign in
-
🚀 10 Powerful Ways to Optimize React Applications (Every Frontend Developer Should Know) React apps can become slow when components re-render unnecessarily or when the bundle size grows. Here are some proven techniques to optimize React performance 👇 1️⃣ Memoization with React.memo Prevents unnecessary re-renders of functional components when props do not change. const MyComponent = React.memo(({ value }) => { return <div>{value}</div>; }); 2️⃣ useMemo Hook Memoizes expensive calculations so they are not recomputed on every render. const sortedList = useMemo(() => { return items.sort(); }, [items]); 3️⃣ useCallback Hook Memoizes functions to prevent unnecessary re-renders in child components. const handleClick = useCallback(() => { setCount(count + 1); }, [count]); 4️⃣ Code Splitting with Lazy Loading Load components only when needed to reduce bundle size. const Dashboard = React.lazy(() => import("./Dashboard")); 5️⃣ Virtualization for Large Lists Use libraries like react-window or react-virtualized to render only visible list items. 6️⃣ Avoid Unnecessary State Keep state minimal and derive values when possible. ❌ Bad const [fullName, setFullName] = useState("") ✅ Good const fullName = firstName + lastName 7️⃣ Key Prop in Lists Always use unique keys to help React efficiently update the DOM. items.map(item => <Item key={item.id} />) 8️⃣ Debouncing and Throttling Improve performance for search inputs and scroll events. Example: lodash debounce 9️⃣ Optimize Images Use compressed images and lazy loading. <img loading="lazy" src="image.png" /> 🔟 Production Build Always deploy optimized production build. #ReactJS #FrontendDevelopment #JavaScript #WebPerformance #Coding #100DaysOfCode #SoftwareEngineering #interview #javascript #post #developer #AI #optimization
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