Day 6: Understanding State in React If Props allow components to receive data, then State allows components to manage and update their own data. 📌 What is State in React? State is a built-in object that allows a component to store data that can change over time. When the state changes, React automatically re-renders the component, updating the UI. 📌 Example using useState Hook import { useState } from "react"; function Counter() { const [count, setCount] = useState(0); return ( <div> <h1>{count}</h1> <button onClick={() => setCount(count + 1)}> Increase </button> </div> ); } 📌 What is happening here? • count → current state value • setCount → function used to update the state • useState(0) → initial value of state When the button is clicked, the state updates and the UI re-renders automatically. 📌 Props vs State Props • Passed from parent component • Read-only State • Managed inside the component • Can be updated 📌 Why State is important State allows React applications to be interactive. Examples: • Counter apps • Form inputs • Toggle buttons • Dynamic UI updates #ReactJS #FrontendDevelopment #JavaScript #WebDevelopment #CodingJourney #LearnInPublic
Understanding React State Management
More Relevant Posts
-
🚀 Understanding useRef in React — Simplified! Not all data in React should trigger a re-render. 👉 That’s where useRef becomes powerful. 💡 What is useRef? useRef is a hook that lets you store a mutable value that persists across renders—without causing re-renders. ⚙️ Basic Syntax const ref = useRef(initialValue); 👉 Access value using: ref.current 🧠 How it works Value persists across renders Updating it does NOT trigger re-render Works like a mutable container 🔹 Example const countRef = useRef(0); const handleClick = () => { countRef.current += 1; console.log(countRef.current); }; 👉 UI won’t update—but value persists 🧩 Real-world use cases ✔ Accessing DOM elements (focus, scroll) ✔ Storing previous values ✔ Managing timers / intervals ✔ Avoiding unnecessary re-renders 🔥 Best Practices (Most developers miss this!) ✅ Use useRef for non-UI data ✅ Use it for DOM access ✅ Combine with useEffect when needed ❌ Don’t use useRef for UI state ❌ Don’t expect UI updates from it ⚠️ Common Mistake // ❌ Expecting UI update countRef.current += 1; 👉 React won’t re-render 💬 Pro Insight 👉 useRef = Persist value without re-render 👉 useState = Persist value with re-render 📌 Save this post & follow for more deep frontend insights! 📅 Day 14/100 #ReactJS #FrontendDevelopment #JavaScript #ReactHooks #useRef #WebDevelopment #SoftwareEngineering #100DaysOfCode 🚀
To view or add a comment, sign in
-
-
🚀 Day 5/30 – State in React One of the most important concepts 🔥 Today I learned: ✅ State stores dynamic data inside a component → It allows components to manage and update their own data ✅ When state changes → React re-renders the UI → React automatically updates only the changed parts (efficient rendering ⚡) ✅ Managed using useState hook → The most commonly used hook in functional components ✅ State updates are asynchronous → React batches updates for better performance 💻 Example: import { useState } from "react"; function Counter() { const [count, setCount] = useState(0); const handleClick = () => { setCount(prev => prev + 1); // safe update }; return ( <div> <h2>Count: {count}</h2> <button onClick={handleClick}>Increment</button> </div> ); } 🔥 Key Takeaway: State is what makes React components interactive, dynamic, and responsive to user actions. #React #State #FrontendDevelopment #JavaScript #WebDev #CodingJourney #LearnInPublic
To view or add a comment, sign in
-
-
🚀 Day 12/30 – Conditional Rendering in React Building dynamic UIs based on conditions ⚡ Today’s focus was on Conditional Rendering — a core concept that makes React apps interactive and user-driven. 🔍 What I learned: ✅ Conditional Rendering allows UI to change based on state ✅ React relies on pure JavaScript logic (if, ternary, &&) inside JSX ✅ Essential for real-world features like authentication, loaders, and error handling 💻 Example: function App() { const isLoggedIn = true; return ( <> {isLoggedIn ? <h1>Welcome User</h1> : <h1>Please Login</h1>} </> ); } 🔥 Common Patterns: 1️⃣ Ternary Operator (Most Used) {condition ? <A /> : <B />} 2️⃣ Logical AND (&&) {isLoggedIn && <Dashboard />} 3️⃣ If Statement (Outside JSX) if (!user) return <Login />; 💡 Real-World Use Cases: ✔️ Showing a loader while fetching data ✔️ Displaying error messages ✔️ Rendering dashboard after login ⚡ Advanced Insight: React doesn’t introduce new syntax for conditions — it simply leverages JavaScript inside JSX, making it flexible and powerful. 🔑 Key Takeaway: 👉 Conditional Rendering = Controlling what users see based on application state. 💬 Curious — which approach do you use more: ternary or if/else logic? #React #FrontendDevelopment #JavaScript #WebDevelopment #LearningInPublic
To view or add a comment, sign in
-
-
Most developers reach for an array by default. But sometimes, that's the wrong tool. When you use array.find() to look up a value, it scans from the start every single time. That's O(n) time complexity. With 10 items, unnoticeable. With 10,000 items, your server feels it. A Map object solves this. Instead of this: const user = users.find(u => u.id === id) Do this: const userMap = new Map(users.map(u => [u.id, u])) const user = userMap.get(id) Map lookups are O(1). It doesn't matter if you have 10 items or 10 million, the lookup time stays the same. This only makes sense when you have a fixed dataset and are doing repeated lookups. If you're looking up once, array.find() is perfectly fine. But if you're hitting that array multiple times, consider reaching for a Map instead. #JavaScript #NodeJS #SoftwareEngineering #WebDevelopment #Performance
To view or add a comment, sign in
-
-
Difference between Normal "var" variable and "UseState" variable in react? Why do we need useState? Can't we just use let count = 0? 🤔 The answer lies in how React renders your application. [1] 💡 Normal Variable (let count = 0) ❌ Changing it does NOT update the screen. ❌ The value resets to 0 every time the component re-renders. ✅ Good for: Internal calculations that don't affect the UI. [1, 2, 3, 4, 5] 💡 State Variable (const [count, setCount] = useState(0)) [1, 2, 3] ✅ Changing it via setCount triggers a UI re-render. ✅ React remembers this value across re-renders. ✅ Good for: Data displayed in JSX (counters, inputs, lists). [1, 2, 3, 4, 5] The Takeaway: If the user needs to see it change, use useState. If it’s just a calculation behind the scenes, a regular variable is fine. [1, 2, 3] jsx // ❌ Won't work in UI var count = 0; const increment = () => count++; // ✅ Will work in UI const [count, setCount] = useState(0); const increment = () => setCount(count + 1); 👇 Have you ever struggled with data not updating in the DOM? #ReactJS #FrontendDevelopment #WebDevelopment #CodingTips #ReactHooks #JavaScript
To view or add a comment, sign in
-
Lazy Loading in React, Boost Performance Like a Pro! Lazy loading is a powerful technique in React where components are loaded only when they are needed, instead of loading everything at once. 👉 Think of it as: Lazy Loading = Code Splitting = Dynamic Imports = On-demand Loading 💡 Why use Lazy Loading? ✔️ Improves performance ✔️ Reduces initial bundle size ✔️ Faster page load experience 🛠️ Key Methods - React.lazy() - for dynamic imports - Suspense - for fallback UI (like loaders) 📌 Basic Syntax const Component = React.lazy(() => import('./Component')); <Suspense fallback={<h1>Loading...</h1>}> <Component /> </Suspense> ⚙️ How it works - Components load only when required - A fallback UI is shown until loading completes 📍 Common Use Cases - Routing (React Router) - Large components - Dashboards ⚠️ Important Points - Works with default exports only - Must be wrapped inside Suspense - It’s a key part of code splitting 🔥 If you are aiming for scalable and high-performance React apps, lazy loading is a must-know concept! #ReactJS #JavaScript #WebDevelopment #FrontendDevelopment #CodeSplitting #PerformanceOptimization #ReactDeveloper #Programming #TechTips #SoftwareDevelopment
To view or add a comment, sign in
-
🧠 Why useRef Doesn’t Cause a Re-render in React Many developers assume useRef behaves like state. But it doesn’t. Example 👇 function Counter() { const countRef = useRef(0); function increment() { countRef.current += 1; console.log(countRef.current); } return ( <button onClick={increment}> Count: {countRef.current} </button> ); } Click the button. Console shows: 1 2 3 But the UI still shows: Count: 0 🔍 Why? useRef does not trigger a re-render. Updating: countRef.current = newValue changes the value, but React does not re-run the component. 🧠 What useRef Is Actually For useRef is mainly used for: Accessing DOM elements Persisting values between renders Storing mutable data that shouldn’t trigger UI updates Example: const inputRef = useRef(); <input ref={inputRef} /> 🎯 Key Rule If the UI needs to update → use state If the value just needs to persist → use ref #ReactJS #FrontendDevelopment #JavaScript #ReactHooks #WebDevelopment #LearningInPublic
To view or add a comment, sign in
-
I wrote the same component 3 times before I realised I only needed to write it once. Days 43–45/100 — 3 days deep into React, and the foundations are finally locking in. Here's everything that clicked this week: 🔹 Fragments — the invisible wrapper React needs a single parent element. But wrapping everything in a <div> pollutes your DOM. <> </> groups your JSX with zero DOM footprint. Clean markup. No ghost divs. No unexpected CSS side effects. 🔹 Map method — lists without the pain In vanilla JS, rendering a list meant loops + manual DOM updates. In React — one .map() call and every item in your array becomes a component. Dynamic. Clean. Automatic. 🔹 Conditional Rendering — 3 tools, 1 goal Making React show the right thing at the right time: • if-else — for complex logic outside JSX • Ternary — clean inline decisions inside JSX • Logical && — show something only when a condition is true Your UI should respond to data — not just display it. 🔹 Passing data via Props Props are how components talk to each other. Parent has data → passes it down → child receives and uses it. Without props, every component is an island. With props, they become a system. 🔹 Destructuring Props Instead of props.name, props.age, props.email everywhere — const { name, age, email } = props. Cleaner. Less repetitive. Readable at a glance. The biggest realisation from these 3 days? A component isn't a fixed UI block. It's a template. Props are the variables. Conditions are the logic. Map is the engine. That's the foundation of almost every React app in production. Day 45 done. 55 to go. 🚀 #100DaysOfCode #ReactJS #MERNStack #WebDevelopment #LearningInPublic #JavaScript #BuildInPublic
To view or add a comment, sign in
-
🚀 Understanding Event Handling in React — Simplified! In React, user interactions drive everything. 👉 Clicking a button 👉 Typing in input 👉 Submitting a form All of this is handled through events. 💡 What is Event Handling in React? Event handling allows you to respond to user actions using functions. <button onClick={handleClick}>Click Me</button> 👉 When clicked → handleClick runs ⚙️ How it works function App() { const handleClick = () => { console.log("Button clicked!"); }; return <button onClick={handleClick}>Click</button>; } ✅ Pass function reference (not function call) ✅ React handles binding automatically 🧠 Key Differences from HTML 🔹 HTML: <button onclick="handleClick()">Click</button> 🔹 React: <button onClick={handleClick}>Click</button> 👉 CamelCase events 👉 Pass functions, not strings 🧩 Common Events in React ✔ onClick → Button click ✔ onChange → Input change ✔ onSubmit → Form submit ✔ onMouseEnter / onMouseLeave ✔ onKeyDown / onKeyUp 🔥 Best Practices (Most developers miss this!) ✅ Always pass function reference ✅ Use arrow functions when needed ✅ Keep handlers clean and reusable ❌ Don’t call function directly in JSX ⚠️ Common Mistake // ❌ Wrong <button onClick={handleClick()}> 👉 This runs immediately instead of on click 💬 Pro Insight React uses a Synthetic Event system: 👉 Normalizes events across all browsers 👉 Improves performance and consistency 📌 Save this post & follow for more deep frontend insights! 📅 Day 9/100 #ReactJS #FrontendDevelopment #JavaScript #WebDevelopment #ReactHooks #SoftwareEngineering #100DaysOfCode 🚀
To view or add a comment, sign in
-
-
🚀 React useEffect Lifecycle Made Simple – Mount, Update & Unmount 🧩 Example: User Profile Component import React, { useState, useEffect } from "react"; function UserProfile() { const [userId, setUserId] = useState(1); const [userName, setUserName] = useState(""); useEffect(() => { console.log("Component Mounted or userId changed"); // Simulate fetching user data const fakeFetch = setTimeout(() => { setUserName("User " + userId); console.log("Fetched data for user", userId); }, 500); // Cleanup on unmount or before next effect return () => { clearTimeout(fakeFetch); console.log("Cleanup: Component Unmounted or userId changed"); }; }, [userId]); return ( <div style={{ border: "1px solid #ccc", padding: "1rem", margin: "1rem" }}> <h2>User Profile</h2> <p>User ID: {userId}</p> <p>User Name: {userName}</p> <button onClick={() => setUserId(userId + 1)}>Next User</button> </div> ); } export default UserProfile; 🔹What Happens Step by Step: Mount: - Component appears on screen - useEffect runs → fetches user 1 → updates name - Console: "Component Mounted or userId changed" Update: - Click button → userId changes → component re-renders - useEffect cleanup runs first → old fetch canceled - New fetch runs → updates UI - Console: "Cleanup: Component Unmounted or userId changed" → " Component Mounted or userId changed " Unmount: - Component removed from screen - Cleanup stops any ongoing fetch/timer → prevents memory leaks - Console: "Cleanup: Component Unmounted or userId changed" #ReactJS #JavaScript #Frontend #WebDevelopment #CleanCode #LearningInPublic #Programming
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