Day 4 — Types of Components in React In React, every UI you build comes from components. There are two main types of components you’ll work with: ⸻ 1. Functional Components (Modern and Most Common) A functional component is a simple JavaScript function that returns UI. It is clean, easy to write, and supports state and lifecycle features through Hooks. Why Functional Components are popular: • Simple and beginner-friendly • Use Hooks like useState and useEffect • Less code, more clarity • Faster and easier to maintain ⸻ 2. Class Components (Older Style, Still Used in Some Projects) A class component is created using ES6 classes. Before Hooks, this was the only way to use state and lifecycle methods. Important points about Class Components: • Use this.state and this.setState • Have lifecycle methods like componentDidMount • Require more code and structure • Still found in older or legacy codebases Quick Comparison Functional Components: clean, modern, and use Hooks Class Components: older, structured, and use lifecycle methods Which type of component do you prefer working with? Share your thoughts in the comments. #100DaysOfCode #ReactJS #FrontendDevelopment #WebDevelopment #ReactComponents #LearningInPublic #LinkedInTechCommunity #JavaScript #ReactForBeginners #KhushiCodes
React Components: Functional vs Class
More Relevant Posts
-
So, you think you know React Hooks? It's easy to use them, but really understanding how they work - that's a different story. I was there too, using React Hooks for a while without truly grasping what they're all about. It wasn't until I dug deeper that things started to click. Here's the thing: Hooks are special functions that React provides. They're like a bridge between your components and React's internal Fiber architecture. And, they register state, side effects, and connect your component logic to React's update system - pretty powerful stuff. Every hook starts with "use" because, well, React treats them differently than normal JavaScript functions. Now, React uses a Fiber Tree to keep track of things, and it stores hooks in a linked list. The order matters - the first hook call is the first node, the second hook call is the second node, and so on. React identifies hooks by their order, not by their name - that's why you can't just use them anywhere. This is where the Rules of Hooks come in: no hooks inside if statements, no hooks inside loops, no hooks after return, and hooks should never be conditionally executed. You can use hooks inside functional components and custom hooks, but not inside normal JavaScript functions - got it? And, there's this thing called the Derived State Trap - if a value can be derived from props or other state, it shouldn't be stored as state. Use functional updates when the new state depends on the previous state, it's just cleaner that way. My mental model is simple: Hooks are nodes in a linked list, React manages that list, and changing the order breaks the system. It's not that hard, once you understand how React's internal design works. The Rules of Hooks aren't arbitrary - they make sense when you know what's going on under the hood. So, if you're struggling with React Hooks, take a step back and learn why they exist, not just how to use them. Trust me, it'll make your code cleaner, reduce bugs, and boost your confidence - it's all about understanding the power of React Hooks. Check out this article for more info: https://lnkd.in/giNXG4gS #JavaScript #WebDevelopment
To view or add a comment, sign in
-
Why Components Matter in React? In React, everything revolves around components. Components help you : 1. Reuse code – write once, use it anywhere 2. Keep the UI organized – small, focused pieces instead of one large file 3. Build scalable applications – easier to grow and maintain over time By breaking the UI into small, reusable components (like Navbar, Button, Card), React makes development cleaner, faster, and more efficient. #ReactJS #FrontendDevelopment #WebDevelopment #JavaScript #LearningReact
To view or add a comment, sign in
-
🗝️ Why Keys Are Important in React Lists (Most Devs Ignore This) If you’ve ever seen weird UI bugs in lists… chances are, keys were the problem 😅 Let’s understand why 👇 🔹 What is a key in React? A key is a unique identifier that helps React track list items. {items.map(item => ( <Item key={item.id} /> ))} 🔹 Why React Needs Keys ✔ Identifies which items changed ✔ Improves rendering performance ✔ Prevents unnecessary re-renders ✔ Avoids UI mismatch bugs 🔹 Common Mistake 🚫 key={index} Using index as key breaks UI when: ❌ Items are reordered ❌ Items are added/removed 💡 Best Practice 👉 Always use a stable & unique id 👉 Only use index as key if the list never changes 📌 Real-World Impact Correct keys = faster UI + fewer bugs 📸 Daily React tips on Instagram: 👉 https://lnkd.in/g7QgUPWX 💬 Do you still use index as key sometimes? Be honest 😄 👍 Like | 🔁 Repost | 💭 Comment #React #ReactJS #FrontendDevelopment #JavaScript #WebDev #ReactTips #DeveloperLife
To view or add a comment, sign in
-
-
React useEffect and setInterval: Why does console.log always print 0? While working with React Hooks, a common point of confusion appears when using setInterval inside useEffect. Problem scenario: useEffect(() => { setInterval(() => { console.log(count) setCount(prev => prev + 1) }, 1000) }, []) Observed behavior: The UI updates correctly and count increments every second However, console.log(count) always prints 0 Root cause: This is not a React issue. It is a result of JavaScript closures combined with an empty dependency array. useEffect([]) runs only once, during the initial render At that time, count is 0 The function passed to setInterval captures (closes over) this initial value As a result, console.log(count) always references the stale state Why the state still updates: The state update uses the functional form: setCount(prev => prev + 1) React guarantees that prev always represents the latest state, which is why the UI continues to update correctly. Recommended approach: When working with intervals, timeouts, or subscriptions, always rely on functional updates or refs instead of directly accessing state variables. Key takeaway: Many React “bugs” are actually misunderstandings of JavaScript fundamentals such as closures and execution context. Understanding this distinction is essential for writing predictable and maintainable React code. #ReactJS #JavaScript #FrontendDevelopment #ReactHooks #useEffect #SoftwareEngineering #WebDevelopment
To view or add a comment, sign in
-
-
🚀 React Fragment vs Div – What Every Developer Should Know When building React applications, choosing the right wrapper can make your components cleaner, faster, and easier to maintain. Here’s a quick comparison: 1️⃣ Div (<div>) Has the prototype chain: HTMLDivElement → HTMLElement → Element → Node → EventTarget Provides extra methods and properties (like innerHTML) Can add keys, classes, styles, and more 2️⃣ React Fragment (<React.Fragment> or <>…</>) Prototype chain: DocumentFragment → Node → EventTarget Eliminates unnecessary wrapper divs → cleaner HTML & better styling Improves performance with less DOM clutter Short syntax (<>…</>) available but cannot use props like key ✅ Advantages of React Fragments: Better code readability and semantic JSX Fewer DOM nodes → improved render performance & lower memory usage Prevents layout issues with CSS Flexbox or Grid Makes your components more logical and modular 💡 Bottom line: Fragments don’t just reduce DOM nodes—they make your UI more maintainable, performant, and professional. In large applications, every small optimization counts! If you’re a React developer looking to write cleaner and faster components, start using Fragments today. #ReactJS #WebDevelopment #FullStack #JavaScript #Frontend #CodingTips #SoftwareEngineering #CleanCode
To view or add a comment, sign in
-
🚀 One simple React optimization that improved performance by ~20% In one of my recent projects, we noticed unnecessary re-renders impacting page load time and user experience. What helped: • Breaking large components into smaller, memoized components • Using React.memo and useCallback where it actually mattered • Implementing lazy loading and code splitting for heavy modules The result? ✔ Faster initial load ✔ Smoother UI interactions ✔ Better maintainability Performance optimization isn’t about over-engineering — it’s about understanding what truly needs to re-render. Curious to know: what’s your go-to React performance tip? 👇 #ReactJS #FrontendDevelopment #WebPerformance #JavaScript #FrontendDeveloper
To view or add a comment, sign in
-
Exciting news for frontend developers! 🚀 The wait is over - Bootbox.js v5.0 is here, bringing seamless integration with Bootstrap 5 and a new custom dialog API. This update enables developers to create programmatic modals with ease. The latest version of Bootbox.js is designed to simplify frontend development, making it a must-have tool for any developer working with Bootstrap. Read more: https://lnkd.in/gKHq5xwg #Bootstrap #Bootboxjs #FrontendDevelopment #WebDevelopment #JavaScript
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
-
🚀 Introducing an NPM Package to Bootstrap Frontend Apps in Minutes Setting up a frontend project usually means repeating the same steps — choosing a stack, configuring folders, and implementing basic authentication flows. To simplify this, I built an NPM package that helps frontend developers scaffold applications quickly and consistently. ⚙️ The package lets you choose: • React or Next.js • JavaScript or TypeScript • Tailwind CSS or SCSS • Axios or RTK Query (Redux Toolkit Query) 📦 What it generates out of the box: • Clean, scalable project structure • Login page • Signup page • OTP verification flow • Static dashboard page 🚀 Get started with one command: npx create-fe-boilerplate@latest The goal is to eliminate repetitive setup work and help developers focus on building real features faster. 😊 I’d really appreciate feedback from the frontend community and suggestions for future improvements. #FrontendDevelopment #ReactJS #NextJS #JavaScript #TypeScript #NPM #WebDevelopment #Redux #RTKQuery #TailwindCSS #OpenSource
To view or add a comment, sign in
-
🚀 **Excited to share my latest open-source contribution!** I've just released **React Modern Toast** v1.5.2 - a powerful, production-ready toast notification library for React and Next.js applications! 🎉 **Key Features:** ✅ Beautiful, consistent UI that works seamlessly in both light and dark modes ✅ Fully accessible with ARIA labels and keyboard navigation ✅ Smart timer with pause-on-hover functionality ✅ 7 customizable positioning options ✅ **Built-in sound effects & speech synthesis** - Different tones for each toast type with customizable volume, rate, pitch, and voice options ✅ Smooth animations and progress indicators ✅ Full TypeScript support (works with JavaScript too!) ✅ Mobile-responsive design ✅ Lightweight bundle size **Try it out:** ```bash npm install react-modern-toast ``` ```tsx import { ToastProvider, toast } from 'react-modern-toast'; import 'react-modern-toast/css'; // Basic usage toast.success('Hello, World!'); // With sound effects toast.success('Success with sound!', { sound: true }); ``` **Works with:** React (v18+), Next.js, TypeScript & JavaScript projects I'm open to feedback, contributions, and feature requests! Let's build better developer experiences together. 💪 #React #TypeScript #OpenSource #WebDevelopment #JavaScript #ReactJS #DeveloperTools #Accessibility #UIUX #FrontendDevelopment #NPM #PackageDevelopment
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