🚀 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 🚀
Priyank Sharma’s Post
More Relevant Posts
-
useState is not for everything. Most React developers make this mistake without even realizing it. They use useState for everything that needs to "store" data. And then wonder why their app re-renders so much. This is Post 9 of the series: 𝗥𝗲𝗮𝗰𝘁 𝗨𝗻𝗱𝗲𝗿 𝘁𝗵𝗲 𝗛𝗼𝗼𝗱 Where I explain what React is actually doing behind the scenes. Here's what actually happens under the hood: 🔵 useState → triggers re-render every time it changes. React watches it. UI updates. But every update = a full render cycle. 🟢 useRef → stores data silently Value persists. But React has no idea it changed. No re-render. 🔴 let variable → resets every single render No persistence. No re-render. Just... gone. Same goal. Very different behaviors. A real-world mistake I see all the time: // ❌ Wrong const [timerId, setTimerId] = useState(null) // ✅ Right const timerRef = useRef(null) Storing a timer ID in state? That causes an unnecessary re-render for data your UI doesn't even show. The simple rule I follow now: 🧠 If it affects the UI → useState 🤫If it's silent data → useRef ⚡ If it's temporary → let variable Wrong choice = silent bugs. Right choice = cleaner, faster React. Next post: useMemo, useCallback, and when React.memo actually helps. Follow Farhaan Shaikh if you want to understand React more deeply. 👉 Read the previous post: Side effects of useEffects: https://lnkd.in/dGGw65aV #React #ReactJS #Frontend #WebDevelopment #JavaScript #BuildInPublic #LearnInPublic #ReactUnderTheHood #FrontendDevelopment #WebDev
To view or add a comment, sign in
-
🚀 Custom Hooks in React — Write Once, Reuse Everywhere As your React app grows… 👉 Logic starts repeating 👉 Components become messy 👉 Code becomes harder to maintain That’s where Custom Hooks come in. 💡 What are Custom Hooks? Custom Hooks are reusable functions that let you extract and share logic between components. 👉 Just like built-in hooks—but created by you ⚙️ Basic Example function useCounter() { const [count, setCount] = useState(0); const increment = () => setCount(c => c + 1); return { count, increment }; } 👉 Use it anywhere: const { count, increment } = useCounter(); 🧠 How it works ✔ Uses existing hooks (useState, useEffect, etc.) ✔ Encapsulates logic ✔ Returns reusable values/functions 🧩 Real-world use cases ✔ API fetching logic (useFetch) ✔ Form handling (useForm) ✔ Debouncing inputs (useDebounce) ✔ Authentication logic (useAuth) 🔥 Why Custom Hooks Matter 👉 Without them: ❌ Duplicate logic across components ❌ Hard to maintain code 👉 With them: ✅ Clean components ✅ Reusable logic ✅ Better scalability 🔥 Best Practices (Most developers miss this!) ✅ Prefix with “use” (important for React rules) ✅ Keep hooks focused on one responsibility ✅ Avoid tightly coupling with UI ❌ Don’t over-abstract too early ⚠️ Common Mistake // ❌ Mixing UI + logic function useData() { return <div>Data</div>; } 👉 Hooks should return data/logic—not JSX 💬 Pro Insight (Senior Thinking) 👉 Components = UI 👉 Hooks = Logic 👉 Clean separation = scalable architecture 📌 Save this post & follow for more deep frontend insights! 📅 Day 18/100 #ReactJS #FrontendDevelopment #JavaScript #ReactHooks #CodeQuality #SoftwareEngineering #100DaysOfCode 🚀
To view or add a comment, sign in
-
-
🚀Why Loading Too Much Data Can Break Your Application While working on an infinite scrolling feature in React, I came across an important real-world problem 👇 ❌ Problem: If the backend sends a very large amount of data at once, both the website and server start slowing down. 🔍 Why does this happen? ▪️ Large API responses take more time to transfer over the network. ▪️The browser struggles to render too many items at once. ▪️Memory usage increases significantly. ▪️Server load increases when handling heavy requests. 👉 I was using the GitHub API, and it helped me understand how important it is to control the amount of data being fetched. 📦 Solution: Pagination + Infinite Scrolling ▪️Instead of loading everything at once: ▪️Fetch data in smaller chunks (pagination) ▪️Load more data only when needed (infinite scroll). ⚡ Benefits: ▪️Faster initial load time ▪️Better performance ▪️Smooth user experience ▪️Reduced server stress 💡 What I learned: ▪️Efficient data fetching is crucial in frontend development ▪️Performance optimization matters as much as functionality ▪️Real-world applications are built with scalability in mind 🎯 Key takeaway: It’s not about how much data you can load — it’s about how efficiently you load it. #ReactJS #JavaScript #WebDevelopment #Frontend #Performance #LearningInPublic #CodingJourney
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
-
-
Most React devs think they understand useEffect. They don't. And it's costing them subtle bugs in prod. Here's the one thing nobody explains clearly: The cleanup function doesn't run when you think it does. Say you're fetching user data based on a userId prop: > the buggy version useEffect(() => { fetch(`/api/user/${userId}`) .then(res => res.json()) .then(data => setUser(data)); }, [userId]); Looks fine, right? It's not. If userId changes from 1 → 2 quickly, maybe the user is clicking through a list, both requests are in flight. Whichever resolves last wins. You could end up showing user 1's data on user 2's profile. That's a race condition, and it's completely silent. Here's how you fix it with an AbortController: > the correct version useEffect(() => { const controller = new AbortController(); fetch(`/api/user/${userId}`, { signal: controller.signal }) .then(res => res.json()) .then(data => setUser(data)) .catch(err => { if (err.name !== 'AbortError') throw err; }); return () => controller.abort(); }, [userId]); Now when userId changes, React runs the cleanup - which aborts the in-flight request, before firing the new effect. No stale data. No race. No mystery bug at 2am. The cleanup function is not just for "removing event listeners." It's your undo button for whatever the effect started. Timers? Clear them. Subscriptions? Unsubscribe. Requests? Abort them. I've seen this bite senior devs on dashboards, search inputs, and paginated lists more times than I can count. If your useEffect fetches data and has no cleanup, there's a bug waiting to happen. #React #MERN #WebDevelopment #JavaScript #FrontendDevelopment #ReactNative
To view or add a comment, sign in
-
🚀 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
-
-
Handling large datasets in React? This is where most applications break. 👉 Performance issues don’t come from React — they come from how we use it. Here’s what actually works in production: ⚡ Memoize Expensive Computations Use useMemo to avoid recalculating heavy logic on every render ⚡ Paginate / Lazy Load Data Load data in chunks instead of rendering everything at once ⚡ Update Only When Necessary Use React.memo and useCallback to prevent unnecessary re-renders 💡 The real goal: 👉 Control re-renders and reduce unnecessary work Because: Large datasets = heavy UI load Uncontrolled renders = lag Optimized updates = smooth experience ⚠️ Common mistakes: ❌ Rendering entire datasets at once ❌ Not using memoization ❌ Poor component structure ✅ What actually matters: Efficient data handling Smart rendering strategy Clean component architecture 💡 In real-world applications, this is the difference between: ❌ Slow, laggy UI ✅ Fast, scalable frontend 👉 React can handle large-scale apps — if you optimize it correctly #ReactJS #FrontendDeveloper #JavaScript #WebDevelopment #SoftwareEngineering #PerformanceOptimization #FrontendArchitecture #TechIndia #Developers
To view or add a comment, sign in
-
-
🌦️ Exploring real-world data with React! Excited to share my Weather App — a project where I worked with APIs to fetch and display live weather data. 🔹 Tech Stack: • React JS • JavaScript • CSS • Weather API 🔹 Features: ✅ Search weather by city ✅ Real-time temperature and conditions ✅ Dynamic UI updates based on data ✅ Clean and responsive design 🌐 Live Demo: https://lnkd.in/gUhuJcYp 🔗 GitHub Repository: https://lnkd.in/gtJQtZbH This project helped me understand how to work with APIs, handle asynchronous data, and build real-world applications using React. Continuing to learn and build more exciting projects 🚀 #react #javascript #webdevelopment #frontend #api #learning #projec
To view or add a comment, sign in
-
Everything looked correct… but we were sending the wrong data to the backend. At some point, you can started noticing something strange in your dashboard. Nothing was obviously broken. The UI updated. The inputs worked as expected.But the data didn’t match what users were typing. Imagine this - you type “John” into a search field. The UI shows “John”. But the API request… still uses the previous value. Here’s a simplified version of what we had: function Dashboard() { const [filters, setFilters] = React.useState({ search: '' }); const fetchData = React.useCallback(() => { api.get('/users', { params: filters }); }, []); React.useEffect(() => { fetchData(); }, [filters]); return ( <input value={filters.search} onChange={(e) => setFilters({ search: e.target.value }) } /> ); } At first glance, it feels correct. The effect depends on filters. Whenever filters change, we fetch data. So what could go wrong? The issue was hiding in a place that looked “optimized”. That useCallback. It was created once, with an empty dependency array. Which means it captured the value of filters at the very beginning… and never updated it. So every time fetchData ran, it used an old version of the filters. That’s why the UI and the backend slowly drifted apart. The user saw one thing. The API received another. The fix was simple: const fetchData = React.useCallback(() => { api.get('/users', { params: filters }); }, [filters]); Or just removing useCallback entirely. What made this bug tricky is that nothing actually crashed.Everything looked fine. But the data was wrong. It was a good reminder that React doesn’t magically keep values up to date inside functions. Closures remember the state from the moment they were created. And sometimes… that’s exactly the problem. Have you run into something like this before? #reactjs #javascript #frontend #webdevelopment #softwareengineering #react #webdev
To view or add a comment, sign in
-
-
I often see frontend performance issues that start as a misunderstanding of boundaries, not a flaw in React or Next.js. The pattern is consistent: server-side data fetching, client-side state, and API orchestration logic get tangled within the same component tree. This creates a cascade of unnecessary re-renders and makes loading states difficult to manage. The problem isn't the framework; it's the architecture. We addressed this by enforcing strict server-client separation in a Next.js 14 application. We moved all initial data fetching and complex computations into Server Components and React `cache()`. Mutations and real-time updates were channeled through stable, dedicated API routes built with the App Router. The key was instrumenting the hydration phase. Using the React DevTools Profiler and custom logging, we measured the cost of client-side JavaScript before optimizing. This revealed that much of the perceived slowness was from over-fetching and re-rendering context providers, not from the server render itself. The result is a clearer mental model and a faster application. Performance gains came from making intentional choices about what runs where, not from micro-optimizations. #NextJS #WebPerformance #React #SoftwareArchitecture #FrontendEngineering #DeveloperExperience #TypeScript #Vercel
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