🚀 Understanding useRef vs useState in React — Simplified! If you're working with React, knowing when to use useRef vs useState can directly impact your app’s performance and rendering behavior. 💡 What is the difference? Both store data across renders—but behave very differently: 🔹 useState → Triggers re-render 🔹 useRef → Does NOT trigger re-render ⚙️ How it works 👉 useState: Stores reactive data Causes component to re-render when updated const [count, setCount] = useState(0); setCount(count + 1); // UI updates 👉 useRef: Stores mutable value Persists across renders Does NOT trigger re-render const countRef = useRef(0); countRef.current += 1; // No UI update 🧠 Real-world use cases ✔ useState: UI state (forms, toggles, counters) Anything that affects rendering ✔ useRef: Accessing DOM (focus, scroll) Storing previous values Managing timers / intervals Avoiding unnecessary re-renders 🔥 Best Practices (Most developers miss this!) ✅ Use useState for UI-driven data ✅ Use useRef for non-visual/mutable values ✅ Use refs to store previous state values ❌ Don’t use useRef when UI needs to update ❌ Don’t overuse state for everything ⚠️ Common mistake // ❌ Wrong approach countRef.current += 1; // UI won't update 👉 If UI depends on it → useState 💬 Pro Insight The real difference is: 👉 useState = Reactive data (triggers render) 👉 useRef = Non-reactive data (no render) 📌 Save this post & follow for more deep frontend insights! 📅 Day 5/100 #ReactJS #FrontendDevelopment #JavaScript #ReactHooks #PerformanceOptimization #SoftwareEngineering #100DaysOfCode 🚀
React Performance: useRef vs useState Best Practices
More Relevant Posts
-
The "Ghost in the API": How I fixed a major rendering lag 👻 While working on a complex user dashboard at Codes Thinker, I encountered a frustrating performance bottleneck. Every time a user triggered a data fetch, the entire UI would "freeze" for a split second before updating. Even with a fast backend API, the user experience felt "heavy" and unprofessional. The Challenge: We were fetching large, nested JSON objects directly inside a parent component. Every time the API responded, the entire component tree re-rendered, causing a visible performance lag during data transformation. The Solution: React Query: I implemented React Query to handle caching. This ensured that if a user requested the same data twice, the result was instant. Data Transformation: Instead of passing the raw "heavy" object to components, I mapped the data into a lighter format immediately after fetching. Optimistic UI: I used Tailwind CSS to create smooth skeleton loaders, making the app feel faster while the data was still loading. The Result: The rendering lag disappeared, and the user experience became fluid. Sometimes, being a Senior Frontend Developer is about knowing when not to fetch data as much as how to fetch it. Have you ever faced a stubborn API lag? How did you tackle it? Let’s share some dev stories! 👇 #RESTAPI #NextJS #PerformanceOptimization #MERNStack #WebDevelopment #CleanCode #ReactJS #TailwindCSS
To view or add a comment, sign in
-
-
For the longest time, my pattern looked like this: • useEffect → call API • useState → store data • loading + error states manually handled It worked… until the app grew. Then came the problems: • duplicate API calls • inconsistent loading states • manual caching (or no caching at all) • refetching logic scattered everywhere That’s when I switched to React Query. — What changed? Server state ≠ UI state React Query made this distinction clear. Caching became automatic Data stays fresh without unnecessary refetching. Background updates UI stays responsive while data syncs silently. Built-in loading & error handling No more boilerplate in every component. Refetching is declarative Not tied to lifecycle hacks anymore. — The biggest mindset shift: Stop thinking: “Where should I fetch this data?” Start thinking: “How should this data behave over time?” — Final takeaway: React Query is not just a library. It’s a different way of thinking about data in frontend. And once you get it, going back to useEffect feels… painful 😅 #reactjs #frontend #javascript #webdevelopment #reactquery #softwareengineering
To view or add a comment, sign in
-
🚀 Understanding Props vs State in React — Simplified! In React, everything revolves around data. But there are two ways to handle it: 👉 Props 👉 State Understanding the difference is crucial for building scalable apps. 💡 What are Props? 👉 Props (short for properties) are used to pass data from parent to child function Greeting({ name }) { return <h1>Hello {name}</h1>; } <Greeting name="React" /> ✅ Read-only ✅ Passed from parent ✅ Cannot be modified by child 💡 What is State? 👉 State is data managed inside a component const [count, setCount] = useState(0); setCount(count + 1); ✅ Mutable ✅ Managed within component ✅ Triggers re-render ⚙️ How it works 🔹 Props: Flow: Parent → Child Immutable Used for communication 🔹 State: Local to component Can be updated Controls UI behavior 🧠 Real-world use cases ✔ Props: Passing data to components Reusable UI components Configuring child behavior ✔ State: Form inputs Toggle UI (modals, dropdowns) Dynamic data 🔥 Best Practices (Most developers miss this!) ✅ Use props for passing data ✅ Use state for managing UI ✅ Keep state minimal and local ❌ Don’t mutate props directly ❌ Don’t duplicate state unnecessarily ⚠️ Common Mistake // ❌ Mutating props props.name = "New Name"; 👉 Props are read-only → always treat them as immutable 💬 Pro Insight 👉 Props = External data (controlled by parent) 👉 State = Internal data (controlled by component) 📌 Save this post & follow for more deep frontend insights! 📅 Day 8/100 #ReactJS #FrontendDevelopment #JavaScript #ReactHooks #WebDevelopment #SoftwareEngineering #100DaysOfCode 🚀
To view or add a comment, sign in
-
-
You're not losing data because of a bug. You're losing it because you never cancelled the request. User types "react" in the search box. Changes their mind. Types "vue". Changes their mind again. Types "angular". Three requests fly in parallel. Come back in random order. "react" arrives last. The UI shows the wrong results. The user sees a bug. You can't reproduce it. This isn't a race condition. These are abandoned requests. Where this is happening in your app right now: Search input — every keystroke fires a request. Only the last one matters. Tab switching — user navigated away, fetch is still running in the new component. Infinite scroll — fast scroll, 8 requests queued, data arrives out of order. Unmount — component is gone, setState fires anyway. React stays silent in production. The mistake I see most often: useEffect with fetch and zero cleanup. Not because the developer doesn't know AbortController exists. Because locally requests are fast and everything looks fine. But the user is on mobile. Or 3G. Or just a slow endpoint. And suddenly response order becomes unpredictable. AbortController doesn't make your requests faster. It guarantees a dead request can't write to a live UI. If the user left — the request should leave with them. #Frontend #JavaScript #React #WebDev #TypeScript #Performance #ReactHooks #WebPerformance
To view or add a comment, sign in
-
-
🚀 Day 26/30 – useReducer (Advanced State Management) When state gets messy… "useState" starts struggling 👀 Today I learned how React handles complex state updates cleanly ⚡ 👉 useReducer --- 💻 The Problem: Managing multiple related states with "useState" ❌ 👉 Too many setters 👉 Scattered logic 👉 Hard to maintain --- 💻 The Solution: Use "useReducer" ✅ 👉 Centralize state logic in one place 👉 Predictable updates 👉 Easier to scale --- 💻 Example: import { useReducer } from "react"; 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: return state; } } function App() { const [state, dispatch] = useReducer(reducer, initialState); return ( <> <h2>{state.count}</h2> <button onClick={() => dispatch({ type: "INCREMENT" })}> + </button> <button onClick={() => dispatch({ type: "DECREMENT" })}> - </button> </> ); } --- 🔥 What actually happens: 1️⃣ User clicks button 2️⃣ dispatch(action) runs 3️⃣ reducer receives state + action 4️⃣ New state returned 5️⃣ UI updates --- 💡 Why this matters: ✅ Better for complex forms ✅ Multiple related states ✅ Cleaner update logic --- ⚡ Real Use Cases: - Shopping cart - Auth flow - Form wizard - Dashboard filters --- ⚡ Advanced Insight: "useReducer" is the same mental model used in Redux 👀 --- 🔥 Key Takeaway: Simple state → useState Complex state → useReducer --- Be honest 👇 Are you still forcing everything into useState? 🚀 #React #useReducer #FrontendDevelopment #JavaScript #StateManagement
To view or add a comment, sign in
-
-
🚨 The “Invisible” Update: Why Your React UI Might Be Stuck Ever faced a bug where you know the data is there… but your UI just refuses to show it? I recently ran into this while working on a table: Data was fetched successfully ✅ Most columns rendered fine ✅ But one column kept showing empty/null ❌ 🕵️♂️ The Culprit: useRef We were storing incoming async data in useRef. At first glance, everything looked correct: Data was arriving ✔ Ref was updating ✔ But here’s the catch 👇 👉 The column that depended on slightly delayed data never re-rendered 👉 So the UI stayed stuck in its initial empty state ⚠️ Why This Happens useRef: Persists values across renders ✅ Does NOT trigger re-render on update ❌ So even when the data eventually arrived, React had no reason to update the UI. ✅ The Fix: Use useState Switched from useRef → useState const [data, setData] = useState(null); Now: As soon as data updates → component re-renders 🔁 Table updates automatically → no more empty column 🎯 #React #FrontendDevelopment #JavaScript #WebDev #SoftwareEngineering
To view or add a comment, sign in
-
Building a high-performance, real-time database visualizer using Next.js 15 and React 19. Take a look at this quick demo of SchemaVis, an open-source project I built to parse complex SQL into interactive diagrams instantly. Building a canvas-heavy application comes with unique challenges. Here is the stack I used to pull it off: 🔹 Next.js 15 (App Router) & React 19: For the core framework and UI rendering. 🔹 XYFlow (React Flow): To handle the complex node-based diagramming, panning, and zooming smoothly. 🔹 node-sql-parser: To safely convert raw SQL strings into actionable ASTs (Abstract Syntax Trees). 🔹 Zustand & TanStack Query: For handling complex client-side state and data fetching. 🔹 Server-Sent Events (SSE): To enable real-time collaboration without the overhead of heavy WebSockets. The result is a lightning-fast alternative to tools like dbdiagram.io or DrawSQL and it's 100% free and open source. 🔗 Live App: https://lnkd.in/deQcwKXZ I'd love feedback from the engineering community on the UX. #SystemDesign #TypeScript #FrontendDevelopment #Engineering #OpenSource #ReactFlow
To view or add a comment, sign in
-
Webix Grid: High Performance That Actually Holds Up Under Pressure https://lnkd.in/dxZzFkKA Most data grids claim performance. Few prove it. In this deep dive, we break down: - Rendering speed with large datasets - DOM stability under stress - Smooth scrolling with real-time updates - Real-world usage scenarios The takeaway: Webix Grid remains fast, stable, and predictable — even when your app isn’t. If you're building data-heavy applications, performance isn’t a feature. It’s the foundation. 👉 Explore benchmarks, demos, and insights #JavaScript #WebDevelopment #Frontend #DataGrid #Performance #WebApps
To view or add a comment, sign in
-
🌤️ Project :Real-Time Weather App I'm excited to share a project I've been working on: a web application that fetches live weather data using a public API! This project was a great way to dive deeper into: API Integration: Successfully pulling real-time data from [ OpenWeatherMap]. Asynchronous JavaScript: Handling data fetching and UI updates seamlessly. Responsive Design: Ensuring the forecast looks great on any device. Check out the live here: [https://lnkd.in/gg4EGpur] #WebDevelopment #JavaScript #APIs #WeatherApp #CodingJourney
To view or add a comment, sign in
-
🚀 Stop treating Server State like UI State. As React developers, we’ve all been there: building "custom" fetching logic with useEffect and useState. It starts with one loading spinner and ends with a nightmare of manual cache-busting and race conditions. When I started migrating my data-fetching to TanStack Query, it wasn't just about "fewer lines of code"—it was about a shift in mindset. The Real Game Changers: Declarative vs. Imperative: Instead of telling React how to fetch (and handle errors/loading), you describe what the data is and when it should be considered stale. Focus Refetching: This is a huge UX win. Seeing data update automatically when a user switches back to the tab feels like magic to them, but it’s just one config line for us. Standardized Patterns: It forces the whole team to handle errors and loading states the same way, which makes code reviews much faster. The Win: In a recent refactor, I replaced a tangled mess of global state syncs and manual useEffect triggers with a few useQuery hooks. I was able to delete a significant chunk of boilerplate while fixing those "stale data" bugs that always seem to haunt client-side apps. The takeaway: Don't reinvent the cache. Use tools that let you focus on the product, not the plumbing. 👇 Question for the devs: Are you using TanStack Query for everything, or are you finding that Next.js Server Actions and the native fetch cache are enough for your use cases now? #reactjs #nextjs #frontend #webdev #tanstackquery #javascript
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