I used to think I understood React state… until this small thing proved me wrong. I wrote this: setCount(count + 1) setCount(count + 1) setCount(count + 1) And I was expecting the count to go up by 3. But it only increased by 1. At first, it made no sense. Then I realized what was actually happening… React doesn’t update state immediately. It batches those updates and runs them later. So all three lines were using the same old value of `count`. Basically, I was doing: 0 → 1, 0 → 1, 0 → 1 Final result: 1 That’s when I learned to use functional updates: setCount(prev => prev + 1) Now each update gets the latest value: 0 → 1 → 2 → 3 Such a small change, but it completely fixed the logic. Since then, I follow one simple rule: 👉 If the new state depends on the previous one, always use a function. It’s one of those things that seems obvious later… but only after it breaks your code once 😅 Curious — has something like this ever confused you in React? #react #javascript
React State Update Gotcha: Using Functional Updates
More Relevant Posts
-
One of the biggest mistakes I made early in React: 👉 Overusing useEffect. After working with React for 3 years, I realized: Most useEffect usage is unnecessary. Here’s when you should NOT use useEffect 👇 ❌ 1. Deriving state from props If you can calculate it directly during render, don’t store it in state. Bad: const [fullName, setFullName] = useState("") useEffect(() => { setFullName(firstName + " " + lastName) }, [firstName, lastName]) Better: const fullName = firstName + " " + lastName ❌ 2. Handling simple calculations React re-renders already — no need for effects. ❌ 3. Updating state based on another state This often leads to unnecessary re-renders or bugs. ✅ When should you use useEffect? API calls Subscriptions (e.g., WebSocket) DOM side effects 💡 Rule I follow now: “If it can be calculated during render, don’t use useEffect.” This one shift made my code: ✔ Simpler ✔ Easier to debug ✔ More performant React is powerful — but only when used correctly. What’s one mistake you used to make in React? #React #FrontendDevelopment #JavaScript #CleanCode #WebDev
To view or add a comment, sign in
-
🧠 React Doesn’t Update State Immediately (Even Inside the Same Function) Most people know state is async. But here’s the part many don’t realize 👇 Example const [count, setCount] = useState(0); function handleClick() { setCount(count + 1); if (count === 0) { console.log("Still zero?"); } } You click the button. Expected: count = 1 But inside that function… 👉 count is still 0 🔍 Why? Because React doesn’t update state inside the current render cycle. It schedules the update and re-renders later. 🧠 The tricky part Even this won’t work: setCount(count + 1); setCount(count + 1); 👉 Final result = +1, not +2 ✅ Correct way setCount(prev => prev + 1); setCount(prev => prev + 1); Now React uses the latest value. 🎯 The Real Insight State inside a function is a snapshot, not a live value. 💥 Why this matters This causes: Unexpected conditions Wrong calculations Confusing bugs #ReactJS #FrontendDevelopment #JavaScript #ReactHooks #WebDevelopment #CodingTips #LearningInPublic
To view or add a comment, sign in
-
🚀 Understanding `useState` & `useEffect` in React If you're working with React, these two hooks are must-know fundamentals: 🔹 **useState** * Used to create and manage state inside a functional component * Returns a state value and a setter function * Triggers re-render when state changes Example: ```js const [count, setCount] = useState(0); ``` 🔹 **useEffect** * Used for side effects (API calls, subscriptions, DOM updates) * Runs after the component renders * Can depend on state or props Example: ```js useEffect(() => { console.log("Component mounted or count changed"); }, [count]); ``` 💡 **Why `useState` should be declared before `useEffect`?** React hooks follow a strict rule: 👉 Hooks must be called in the same order on every render. Since `useEffect` often depends on state values, defining `useState` first ensures: * State is initialized before being used * Dependencies inside `useEffect` are available * Hook order remains consistent (avoiding bugs or crashes) ⚠️ Breaking hook order can lead to unexpected behavior and hard-to-debug issues. ✅ Always follow: 1. Declare state (`useState`) 2. Then handle side effects (`useEffect`) --- Mastering these basics makes your React apps more predictable and maintainable 💻✨ #React #JavaScript #WebDevelopment #Frontend #Programming #ReactHooks
To view or add a comment, sign in
-
I Thought This Was Easy ! Date: 9/4/2026 Today, I tried another React.js project: Transfer List. When I saw it for the first time, I realized this is too easy—only a game with array, and state updates. 😎 But? When I tried it, I got stuck ! 🤣 🤣 The first two functionalities—moving all items from the left box to the right box and vice versa—I made easily. 😊 But moving only checked items was the most challenging part of this project.🤔 Disabling buttons based on conditions (most time-consuming). After making this project, what I learned: 👉 Improved logical thinking about states. 👉 I learned why the Double-Bang operator is important. 👉 Strong command of filtering. And from what I know, these are the weak areas where improvement is required: 👉 Controlled Components 👉 I always use useState; I need to practice useReducer more. Github Repo - https://lnkd.in/gK9cqYxm #ReactJS #WebDevelopment #CodingJourney #JavaScript #CodeNewbie
To view or add a comment, sign in
-
🚀 Leveling up my React JS knowledge! Here's what I learned this week — explained simply 👇 ⚛️ 1. Reconciliation React doesn't re-render the entire DOM every time. It compares the old and new Virtual DOM, finds the difference, and updates ONLY what changed. Result? Blazing fast UI! 🔥 🔄 2. Batch Updating React is smart — it groups multiple state updates together and re-renders ONCE instead of multiple times. Fewer re-renders = better performance! 💡 👶 3. Children Prop Want to pass content between component tags? That's the children prop! It makes components flexible and reusable — like a wrapper that accepts anything inside it. 🎛️ 4. Controlled vs Uncontrolled Inputs ✅ Controlled → React controls the input value via state. You're in full control. ❌ Uncontrolled → The DOM handles the value using refs. Less code, less control. Controlled inputs = predictable, testable, and recommended! ✅ Every concept I learn makes me a better developer. 💪 Still learning. Still growing. 🌱 #ReactJS #JavaScript #WebDevelopment #Frontend #100DaysOfCode #LearningInPublic
To view or add a comment, sign in
-
-
Props vs State in React Most beginners get confused between Props and State in React. At first, both seem similar because both store data. But the real difference is simple: * Props = Data received from another component * State = Data managed inside the component Example: function Parent() { return <Child name="Durgesh" />; } function Child(props) { return <h1>{props.name}</h1>; } Here, `name` is a prop because it comes from the Parent component. Now look at State: const [count, setCount] = useState(0); Here, `count` is managed inside the same component. Quick Difference 👇 • Props are read-only • State can be updated • Props come from parent to child • State belongs to the component itself Think like this: Props = Things you receive State = Things you control Once you understand this difference, React becomes much easier. What confused you more when learning React — Props or State? #react #javascript #frontend #webdevelopment #reactjs #coding
To view or add a comment, sign in
-
-
Mastering useState: The Most Important Hook in React If you're working with React, useState is one of the first hooks you learn — and also one you’ll use in almost every component you build. Yet many developers still use it incorrectly and run into stale state or unnecessary re-renders. useState allows you to add state to functional components. It returns an array with two values: the current state and a setter function. const [count, setCount] = useState(0); The real power (and common pitfall) comes when your new state depends on the previous state. Correct way: Using the functional updater (prev) => guarantees you always get the latest state, even when multiple updates happen quickly. A few best practices I always follow: Never mutate state directly. Always create a new object/array using the spread operator (...prev). Use computed property names [dynamicKey] when your key comes from a variable. Keep state as simple as possible. If your state object gets too complex, consider useReducer. I’ve seen many bugs disappear simply by switching from setState(newValue) to the functional form when the update relies on previous values. Whether you’re building a small UI or a complex audio/video player like the one I was recently working on, mastering useState patterns makes your code more predictable, cleaner, and easier to debug. What’s one useState trick or gotcha you’ve learned? Drop it in the comments #React #JavaScript #WebDevelopment #Frontend #CodingTips
To view or add a comment, sign in
-
-
🚨 Small React mistake… big headache 👇 I used to write code like this without even thinking: if (condition) return null; useEffect(() => { // logic }, []); It looks completely fine, right? I thought the same ❌ Then suddenly this error shows up: 👉 "Rendered fewer hooks than expected" Took me some time to realize what was actually wrong. React expects hooks to run in the same order every single render. But in this case: • First render → component returns early → useEffect doesn’t run • Next render → useEffect runs And boom 💥 React gets confused because the order changed. The fix is simple (but easy to forget): useEffect(() => { // logic }, []); if (condition) return null; Now hooks always run first, no matter what 👍 💡 Lesson learned: Never put hooks after a condition or inside it. Always keep them at the top. Have you ever hit this error? It’s one of those bugs that looks small but wastes a lot of time 😅 #react #nextjs #javascript #frontend #webdev
To view or add a comment, sign in
-
-
most React developers use useCallback wrong. not because they don't understand it. because they were taught the wrong rule. the rule they heard: "wrap functions in useCallback to prevent unnecessary re-renders. the actual rule: useCallback only helps when you pass that function to a child component wrapped in React.memo or as a dependency in useEffect. that's it. useCallback doesn't prevent re-renders of the parent. it just memoizes the function reference so children don't see a "new" function every render. three questions to ask before reaching for useCallback: - is this function passed to a memoized child component? - is this function a dependency in a useEffect? - is this function expensive to recreate? if none of these just write the function normally. the best optimisation is usually the one you don't add. #reactjs #typescript #webdevelopment #buildinpublic #javascript
To view or add a comment, sign in
-
-
when I first started React I was so confused about useState and useEffect like what is the difference and when do I use which one so let me explain both with one simple real example 👇 imagine you are building a weather app that fetches weather data when the page loads here is how useState and useEffect work together in that const [weather, setWeather] = useState(null) useEffect(() => { fetch('https://lnkd.in/g7JkAAtU') .then(res => res.json()) .then(data => setWeather(data)) }, []) that is it. two hooks. one job each. useState stores the weather data useEffect fetches it when the component loads simple way to remember it 👇 useState = where you keep your data useEffect = where you do something when something happens when I understood this everything in React started making sense if you are just starting React and feeling confused about these two, save this post. you will need it 🙌 anything else in React that confused you when you started? drop it in the comments 👇 #React #JavaScript #Frontend #WebDev #ReactJS #100DaysOfCode #Programming #LearnToCode
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