Why does this confuse people in React? Because it behaves very differently in classes vs hooks. 🧠 In React Class Components this refers to the component instance class Counter extends React.Component { state = { count: 0 }; increment() { this.setState({ count: this.state.count + 1 }); } render() { return <button onClick={this.increment}>+</button>; } } ❌ This breaks because this is lost in callbacks Fix it by: binding in constructor or using arrow functions increment = () => { this.setState({ count: this.state.count + 1 }); }; So in classes: this exists this must be bound correctly 🧠 In React Hooks (Functional Components) There is no this function Counter() { const [count, setCount] = useState(0); return <button onClick={() => setCount(count + 1)}>+</button>; } Why? Functions don’t create component instances State is handled via closures No binding issues Much simpler mental model Hooks removed this from React because this was a common source of bugs, confusion, and boilerplate. If you understand this, React suddenly feels… calmer 😌 #reactjs #javascript #frontend #interviewprep
React Class vs Hooks: Understanding 'this' Behavior
More Relevant Posts
-
🦕 Remember componentDidMount? If you started React recently, you might not. React has evolved significantly. We moved from the explicit lifecycle methods of Class Components to the sleek synchronization engine of Functional Components and Hooks. But understanding the Lifecycle is still crucial to mastering useEffect. The Three Phases of a Component: 1️⃣ Mounting (Birth): The component is created and inserted into the DOM. - Old: componentDidMount - New: useEffect(() => { ... }, []) (Empty dependency array) 2️⃣ Updating (Growth): The component re-renders because props or state changed. - Old: componentDidUpdate - New: useEffect(() => { ... }, [prop, state]) (Array with dependencies) 3️⃣ Unmounting (Death): The component is removed from the DOM. - Old: componentWillUnmount - New: useEffect(() => { return () => { ... } }, []) (The cleanup function) The Mental Shift: Instead of thinking "When does this run?" (Time-based), try thinking "What is this synchronized with?" (State-based). Which syntax do you find easier to reason about? #ReactJS #WebDevelopment #Frontend #JavaScript #CodingTips #Hooks
To view or add a comment, sign in
-
-
React State Is a Snapshot — Not a Variable (A Concept Every React Dev Should Know) One of the most misunderstood concepts in React is that state is a snapshot in time, not a mutable variable. When React renders a component, it gives you a snapshot of: props state event handlers That snapshot is fixed for that render. setCount(count + 1); setCount(count + 1); setCount(count + 1); You might expect count to increase by 3 — but it doesn’t. Why? Because all three updates read the same snapshot of count. The Correct Mental Model State updates are queued React re-renders later with a new snapshot Code inside the same render never sees updated state The Fix: Functional Updates setCount(prev => prev + 1); setCount(prev => prev + 1); setCount(prev => prev + 1); Now React applies each update to the latest value, not the old snapshot. Why This Matters Understanding state as a snapshot helps you: Avoid stale state bugs Write predictable event handlers Fix issues with async logic, debouncing, and batching Reason better about concurrent rendering in React 18+ Key Takeaway State doesn’t change inside a render. React gives you a snapshot — and the next render gives you a new one. Once this clicks, many “weird” React bugs suddenly make sense. #ReactJS #Frontend #JavaScript #WebDevelopment #ReactHooks #React18
To view or add a comment, sign in
-
⚛️ When NOT to Use React Hooks React Hooks are powerful, but using them everywhere is not always the best choice. While building and refactoring components, I learned that knowing when not to use a hook is just as important as knowing how to use one. Here are some real cases where I avoid hooks: ❌ Don’t use useEffect for derived data If a value can be calculated from props or state, it doesn’t belong in useEffect. ❌ Don’t use useState for static values Constants and fixed values don’t need a state. ❌ Don’t use useMemo or useCallback prematurely Optimization hooks should solve real performance issues—not be added by default. ❌ Don’t use useRef to control UI Refs are for storing mutable values, not for triggering re-renders. ❌ Don’t add hooks just because you can Cleaner logic always beats more hooks. ✨ Key lesson: Good React code is not about using more hooks — it’s about writing simpler, more predictable components. How do you decide when a hook is really needed? #React #ReactHooks #WebDevelopment #JavaScript #Frontend #CleanCode #LearningJourney
To view or add a comment, sign in
-
-
⚛️ When NOT to Use React Hooks React Hooks are powerful, but using them everywhere is not always the best choice. While building and refactoring components, I learned that knowing when not to use a hook is just as important as knowing how to use one. Here are some real cases where I avoid hooks: ❌ Don’t use useEffect for derived data If a value can be calculated from props or state, it doesn’t belong in useEffect. ❌ Don’t use useState for static values Constants and fixed values don’t need a state. ❌ Don’t use useMemo or useCallback prematurely Optimization hooks should solve real performance issues—not be added by default. ❌ Don’t use useRef to control UI Refs are for storing mutable values, not for triggering re-renders. ❌ Don’t add hooks just because you can Cleaner logic always beats more hooks. ✨ Key lesson: Good React code is not about using more hooks — it’s about writing simpler, more predictable components. How do you decide when a hook is really needed? #React #ReactHooks #WebDevelopment #JavaScript #Frontend #CleanCode #LearningJourney
To view or add a comment, sign in
-
-
✍️ React Hook Form – quick notes from today Forms in React always felt… heavy 😅 Too many states, too many re-renders. Then I met React Hook Form. What I liked instantly: Minimal re-renders Less boilerplate Easy validation Works great with UI libraries Instead of controlling every input, React Hook Form lets the browser do its job. const { register, handleSubmit } = useForm() <form onSubmit={handleSubmit(onSubmit)}> <input {...register("email")} /> </form> That’s it. No unnecessary useState. Feels lightweight, clean, and very React-friendly. Still learning, but this already feels like the right way to build forms. #ReactJS #ReactHookForm #Frontend #WebDevelopment #LearningInPublic #JavaScript
To view or add a comment, sign in
-
-
React 19 brought several nice features worth mentioning. One of the most interesting additions is the "use" hook, which is especially helpful in scenarios like async data fetching. In previous versions of React, handling async logic often required a fair amount of boilerplate code: managing loading and error states manually, writing conditional rendering logic, and keeping everything in sync. With the new approach, an async call can be wrapped directly in the "use" hook, while the component that contains it should be wrapped with the Suspense component. This results in much cleaner and more readable code, without changing the final behavior. Less code, same effect. Just don’t forget to properly handle promise rejections, as unhandled errors can still cause issues 😉 https://lnkd.in/dqpYEK99 BTW, the new "use" hook can also be rendered conditionally — you can place it inside an if statement, which opens up even more flexible patterns.
Software Engineer @ Gamyam | MERN Stack Developer | Building Scalable Web Apps & AI-Powered Features | Python • SQL • DSA | NCC Cadet 🎖️
🚀 React Update: useEffect vs the new use() hook Frontend devs — have you explored the new use() hook in React 19? Here’s a simple comparison for modern data handling ⚛️ Old vs New For years, fetching data meant: • Managing useState • Writing useEffect boilerplate • Manually handling loading states All of that… just to render data. React 19 changes the game. With the new use() hook: ✅ Cleaner, more readable code ✅ No side-effect-heavy logic ✅ Loading handled automatically with Suspense Less noise. More focus on UI and intent. Sometimes progress isn’t about adding features — it’s about removing friction. 👀 Which syntax do you prefer reading: the old pattern or the new one? Drop your thoughts in the comments 👇 #ReactJS #Frontend #WebDevelopment #JavaScript #Coding #React19 #LearnInPublic
To view or add a comment, sign in
-
-
⚡ React isn't faster because it's smarter. It's faster because it's lazy. We hear the word "Reconciliation" thrown around in React interviews, but what does it actually mean? Here is the truth: Updating the Real DOM is slow. Extremely slow. 🐢 React’s goal is to touch the Real DOM as little as possible. How Reconciliation Works (The 3-Step Dance): - Render Phase: When state changes, React creates a new Virtual DOM tree. This is just a lightweight JavaScript object—it's fast and cheap to create. - The "Diffing" Phase: React compares the New Virtual DOM with the Old Virtual DOM. It plays a game of "Spot the Difference." "Did the parent change?" -> No. "Did the first child change?" -> No. "Did the text in the second child change?" -> YES! 🚨 - Commit Phase: React updates the Real DOM, but only changes that specific text node. It leaves the rest of the page alone. The "Key" Prop Mystery 🔑 Why does React yell at you for missing key in lists? Without keys, if you insert an item at the top of a list, React thinks every single item changed and re-renders them all. With unique keys, React says: "Oh, item #100 just moved to the top. I'll just move that one node." Reconciliation is the art of doing the bare minimum. And in software performance, laziness is a virtue. #ReactJS #Frontend #WebDevelopment #Reconciliation #Performance #Javascript #CodingInterview
To view or add a comment, sign in
-
-
I recently revisited the React countdown timer. It reminded me of a mistake many of us have made at least once. Two common problems with timers in React - Memory leaks - Stale state caused by JavaScript closures The closure problem: When we create setInterval, the callback captures variables at creation time. So setInterval(() => { setRemainingMs(remainingMs - 1000) }, 1000) This looks okay, but it is incorrect. Because remainingMs inside a closuer is frozen. The interval keeps the old value even after React re-renders. So this leads to - Frozen timers - Skipped seconds - Incorrect UI state The correct fix: use functional state update: setRemainingMs(prev => Max.max(prev-1000, 0)) Preventing Memory Leaks: If we create something in useEffect (intervals, listeners, subscriptions), we must clean it up: return () => clearInterval(interval) Otherwise, the timer keeps running even after the component unmounts. How I remember: - If state depends on previous state -> use functional updates - If I create side effects -> I must clean them up So, React did not break my timer; JavaScript closures did, React just made them visible. If this saved you from a future bug, it was worth sharing #React #JavaScript #Frontend #WebDevelopment #CleanCode #development #devnote
To view or add a comment, sign in
-
I thought I was writing clean React. I opened the React Profiler and found a silly thing causing extra rerenders. Last week I reviewed a laggy screen (inputs felt delayed, clicks weren’t instant). The component looked “best-practice”: - useCallback - memoized props - React.memo in the tree But one detail killed it: Inline objects inside JSX.... When a child relies on shallow prop comparison (like React.memo), a new object reference on every render breaks memoization, even if the values are identical. After making the prop reference stable, renders dropped ~40% on that screen. Lesson: performance isn’t always about fancy tricks. Sometimes it’s just avoiding accidental work. What’s a “small” thing you’ve seen tank performance? #React #Performance #Frontend #JavaScript
To view or add a comment, sign in
-
-
Why setState(prev => …) Exists (And When You MUST Use It) ⚛️ Ever written this and expected +2? setCount(count + 1); setCount(count + 1); But React gave you +1 😵💫 React isn’t broken. Your mental model is. What’s actually happening 👇 Remember this rule: Each render sees its own snapshot of state 📸 In that render: count has one fixed value Both updates read from the same snapshot So React sees: setCount(0 + 1); setCount(0 + 1); ➡️ Result: 1, not 2 Why the functional updater exists 🧠 Now look at this: setCount(prev => prev + 1); setCount(prev => prev + 1); This time, React does this internally: First update → prev = 0 → 1 Second update → prev = 1 → 2 Why? Because the updater function: Runs after React processes the queue Always receives the latest state, not a stale snapshot When you MUST use prev => … ✅ Use the functional updater whenever: The next state depends on the previous state You’re doing multiple updates in a row Updates happen inside async code (setTimeout, promises, events) 💡 The real takeaway setState(value) says: “Set state to this value” setState(prev => next) says: “Calculate the next state from the latest reality” If React state feels confusing, it’s usually because you’re thinking in variables — not renders. 💬 Question for you: When did this bug first bite you? #ReactJS #JavaScript #WebDevelopment #FrontendDevelopment #CodingTips #SoftwareEngineering #CodingBlockHisar
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