𝐑𝐞𝐚𝐜𝐭 𝐇𝐨𝐨𝐤𝐬 𝐈𝐧𝐭𝐞𝐫𝐯𝐢𝐞𝐰 𝐐𝐮𝐞𝐬𝐭𝐢𝐨𝐧 🤔 Many developers use useState and useRef… but don’t know the real difference. Question: What is the difference between useState and useRef? And which one causes re-render? Example 👇 import React, { useState, useRef } from "react"; export default function App() { const [count, setCount] = useState(0); const refCount = useRef(0); console.log("Render"); return ( <> <button onClick={() => setCount(count + 1)}> useState + <button onClick={() => { refCount.current += 1; console.log(refCount.current); }}> useRef + </button> </> ); } What happens here? Click useState button → Component re-renders Click useRef button → Component does NOT re-render Why? useState → updates state and re-renders component useRef → updates value without re-render Tip for Interview: useRef is used for storing mutable values without causing re-render. Good developers know hooks. Great developers know when to use them. #ReactJS #ReactHooks #useState #useRef #FrontendDeveloper #JavaScript #ReactInterview #CodingInterview #WebDevelopment
useState vs useRef in React: Understanding the Difference
More Relevant Posts
-
𝐓𝐫𝐢𝐜𝐤𝐲 𝐑𝐞𝐚𝐜𝐭 𝐂𝐥𝐨𝐬𝐮𝐫𝐞 𝐈𝐧𝐭𝐞𝐫𝐯𝐢𝐞𝐰 𝐐𝐮𝐞𝐬𝐭𝐢𝐨𝐧 🤔 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
-
🚀 Why useState is a Game-Changer in React. let's breakdown this 👇 💡 What is useState? "useState" is a React Hook that allows you to store and manage dynamic data (state) inside functional components. Without it, your UI wouldn’t respond to user input. 📱 Real-Time Example: Form Input & Validation Let’s take a simple login form 👇 import React, { useState } from "react"; function LoginForm() { const [email, setEmail] = useState(""); const [error, setError] = useState(""); const handleSubmit = (e) => { e.preventDefault(); if (!email.includes("@")) { setError("Please enter a valid email address"); } else { setError(""); alert("Form submitted successfully!"); } }; return ( <form onSubmit={handleSubmit}> <input type="text" placeholder="Enter email" value={email} onChange={(e) => setEmail(e.target.value)} /> {error && <p style={{ color: "red" }}>{error}</p>} <button type="submit">Submit</button> </form> ); } export default LoginForm 🧠 What’s happening here? - "email" → stores user input - "setEmail" → updates input as the user types - "error" → stores validation message - "setError" → shows/hides error instantly useState is what connects user actions to UI behavior. It ensures your forms are not just functional, but smart and responsible 💬 Have you implemented form validation using useState? What challenges did you face? #ReactJS #FrontendDevelopment #JavaScript #WebDevelopment #Coding
To view or add a comment, sign in
-
𝐓𝐫𝐢𝐜𝐤𝐲 𝐑𝐞𝐚𝐜𝐭 𝐈𝐧𝐭𝐞𝐫𝐯𝐢𝐞𝐰 𝐐𝐮𝐞𝐬𝐭𝐢𝐨𝐧 🤔 Most developers use React.memo… but don’t fully understand it. Question: Does React.memo always stop re-render? Example 👇 import React, { useState } from "react"; const Child = React.memo(({ value }) => { console.log("Child render"); return <div>{value}</div>; }); export default function Parent() { const [count, setCount] = useState(0); return ( <> <button onClick={() => setCount(count + 1)}> Click </button> <Child value={10} /> </> ); } What happens when button is clicked? Answer 👇 Parent will re-render But Child will NOT re-render Why? Because React.memo prevents re-render when props do not change. Now tricky part ⚠️ <Child value={{ num: 10 }} /> In this case Child WILL re-render because object reference changes every render. Tip for Interview: React.memo does shallow comparison. If props reference changes, component re-renders. Good developers know React. Great developers know how React renders. #ReactJS #ReactMemo #FrontendDeveloper #JavaScript #WebDevelopment #ReactInterview #CodingInterview #NextJS #SoftwareDeveloper
To view or add a comment, sign in
-
-
🚀 Understanding "useState" in React (Made Simple) When I started learning React, one concept that really clicked for me was "useState". 👉 Think of "useState" as a small memory inside your component that keeps track of changing data. It helps you: ✔️ Store data (like count, input text, etc.) ✔️ Update that data easily ✔️ Automatically reflect changes on the UI 💡 Without "useState", your UI would remain static and wouldn’t respond to user actions. Here’s a quick example: const [count, setCount] = useState(0); - "count" → current value - "setCount" → function to update it Every time the state updates, React re-renders the component and displays the latest value instantly. 🎯 In one line: "useState" makes your UI dynamic, interactive, and user-friendly. #React #JavaScript #FrontendDevelopment #WebDevelopment #LearnInPublic #CodingJourney
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
-
🤔 useMemo and useCallback confuse almost every React developer. Here’s the clearest way to think about it 👇 🧠 Core idea: → useMemo = cache a VALUE → useCallback = cache a FUNCTION REFERENCE 💻 Example: // useMemo — don't recalculate unless deps change const total = useMemo(() => cart.reduce((sum, item) => sum + item.price, 0), [cart] ); // useCallback — don't recreate unless deps change const handleClick = useCallback(() => { doSomething(id); }, [id]); 🎯 When to use useCallback: When you pass a function to a React.memo’d child Without it 👇 ➡️ A new function is created every render ➡️ React.memo becomes useless ⚠️ Common mistake: Wrapping everything in useMemo / useCallback “just in case” 💡 Reality check: Both hooks have a cost Use them only when: ✔️ You’ve identified a real performance issue ✔️ You’ve actually measured it 📌 Rule: Premature optimization ≠ good engineering #ReactJS #Hooks #JavaScript #FrontendDev
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 ( <> <button onClick={handleClick}> Click </button> <button onClick={() => setCount(count + 1)}> Increase Count ({count}) </button> </> ); } 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 ✅ useEffect(() => { const id = setInterval(() => { console.log(count); }, 1000); return () => clearInterval(id); }, [count]); 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
-
-
𝐓𝐡𝐢𝐧𝐤𝐢𝐧𝐠 `React.memo` 𝐦𝐚𝐤𝐞𝐬 𝐲𝐨𝐮𝐫 𝐜𝐨𝐦𝐩𝐨𝐧𝐞𝐧𝐭𝐬 𝐩𝐞𝐫𝐟𝐞𝐜𝐭𝐥𝐲 𝐩𝐞𝐫𝐟𝐨𝐫𝐦𝐚𝐧𝐭? 𝐓𝐡𝐢𝐧𝐤 𝐚𝐠𝐚𝐢𝐧. Many of us reach for `React.memo` to prevent unnecessary re-renders in child components. And it works wonders... most of the time. But here's the catch: `React.memo` performs a shallow comparison of props. If you're passing object, array, or function props, even if their internal values haven't changed, a new reference is created on every parent re-render. This new reference makes `React.memo` think the prop has changed, leading to an unwanted re-render of your memoized child component. ```javascript // Parent component re-renders: const data = { id: 1, name: 'Item' }; // New object reference! <MemoizedChild item={data} /> // Or with a function: const handleClick = () => console.log('clicked'); // New function reference! <MemoizedChild onClick={handleClick} /> ``` The solution? Pair `React.memo` with `useCallback` for functions and `useMemo` for objects/arrays. ```javascript // In Parent component: const memoizedData = useMemo(() => ({ id: 1, name: 'Item' }), []); const memoizedHandleClick = useCallback(() => console.log('clicked'), []); <MemoizedChild item={memoizedData} onClick={memoizedHandleClick} /> ``` This ensures your props maintain the same reference across renders, allowing `React.memo` to truly shine. It's a small detail, but crucial for optimizing complex applications. How aggressively do you memoize in your React apps? Share your go-to strategies! #React #ReactJS #FrontendDevelopment #WebPerformance #JavaScript
To view or add a comment, sign in
-
I've been using Next.js for over a year. These 5 features changed how I build apps completely. 🧵 Most devs I know are still doing things the hard way. Here's what you should be using instead: 1. Server Components — fetch data directly in your component. No useEffect, no loading states, no extra API calls. 2. Parallel Routes — render multiple pages in the same layout simultaneously. Perfect for modals and dashboards. 3. Route Handlers — built-in API routes. No need for a separate backend for simple operations. 4. generateMetadata — dynamic SEO for every page. Stop hardcoding your meta tags. 5. Server Actions — submit forms and mutate data without writing a single API endpoint. I wasted months not knowing these existed. Don't make the same mistake. 💪 Which one are you already using? Drop it below 👇 #NextJS #ReactJS #WebDevelopment #FullStackDeveloper #TypeScript #JavaScript #Frontend #100DaysOfCode #BuildInPublic #LahoreTech
To view or add a comment, sign in
-
-
🚨 React Interview Question That Confuses 90% Developers Let’s test your React fundamentals 👇 import { useState } from "react"; export default function App() { const [count, setCount] = useState(0); function handleClick() { setCount(count + 1); setCount(count + 2); setCount(count + 3); console.log(count); } return ( <> <h1>{count}</h1> <button onClick={handleClick}>Click</button> </> ); } 👉 What will be the output? 1️⃣ Console output? 2️⃣ Final UI value? ⚡ Bonus: Why doesn’t it become 3 (or even 6)? 👇 Think before reading the answer 👇 — — — — — — — — — — — — ✅ Answer Console → 0 UI → 3 🧠 Why? React batches state updates and treats them as async. All setCount calls use the same stale value (count = 0). So internally: 0 + 1 = 1 0 + 2 = 2 0 + 3 = 3 ✅ (last update wins) 🔥 Correct way (if you want cumulative updates): setCount(prev => prev + 1); setCount(prev => prev + 1); setCount(prev => prev + 1); 👉 Now React updates sequentially → Final = 3 💬 Takeaway: • State updates are async • React batches updates • Avoid stale values • Use functional updates when chaining Did you get it right? 👀 #ReactJS #FrontendInterview #JavaScript #ReactHooks #FrontendDeveloper
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