Class-08 'Let's get classy' from the Namaste React course by Akshay Saini 🚀 01. How do you create Nested Routes react-router-dom cofiguration? npm i react-router Create a router and pass it to RouterProvider: import React from "react"; import ReactDOM from "react-dom/client"; import { createBrowserRouter } from "react-router"; import { RouterProvider } from "react-router/dom"; const router = createBrowserRouter([ { path: "/", Component: Root, children: [ { index: true, Component: Home }, { path: "about", Component: About }, { path: "auth", Component: AuthLayout, children: [ { path: "login", Component: Login }, { path: "register", Component: Register }, ] }, { path: "concerts", children: [ { index: true, Component: ConcertsHome }, { path: ":city", Component: ConcertsCity }, { path: "trending", Component: ConcertsTrending } ] } ] } ]) const root = document.getElementById("root"); ReactDOM.createRoot(root).render( <RouterProvider router={router} /> ); 02. What is the order of life cycle method calls in Class Based Components? 1. constructor function 2. calling super function to initializes parent's constructor. 3. render method. (Mandatory) 4. React DOM (return JSX from the render method) 5. componentDidMount(){} 6. componentDidUpdate(){} 7. componentWillUnmount(){} 03. Why do we use componentDidMount? After initial rendering/mounting a component to the UI(i.e, DOM) we atleast showed something on the UI to the user, now background API calls, timers, subscriptions or any asynchronous operations to happen, we put them inside it. After successful completion of the function, we can set the state it re-render the component, updates will be reflected in the UI. 04. Why do we use componentWillUnmount? Show with example We use this function to clearup any function that needs to be end, before unmounting a component. Also, this prevents memory leak, affects app performance. 05. Why do we use super(props) in constructor? super(props) is not Mandatory in modern react code. Whenever we use constructor for writing customize initial values in the component/class. We must use super() to initializes parent component (React.component) constructor function. This setup initial values and state in the constructor function. 06. Why can't we have the callback function of useEffect async? useEffect hook callback function designed to return nothing (undefined) or cleanup function. However async function can be written inside the hook, that is declared and called inside it. Please have a look at my github repo at the 'branch 08' I've shared all my assignments. #frontend #reactdeveloper #reactjs #javascript #jsx
React Router Configuration and Class Component Lifecycle Methods
More Relevant Posts
-
🚀 React State Management: What I Learned After Working on Large Applications When I started working with React, I used Redux for almost everything — API responses, form data, modal states, filters, theme settings, and more. At first, it felt organized because everything was in one place. But as projects became bigger, managing all state in one store started creating complexity. One important lesson I learned: not all state should be handled the same way. ✅ Server State Data coming from APIs like user details, reports, dashboard data, etc. Best handled with tools like React Query / RTK Query for caching, refetching, and synchronization. ✅ Client State Local UI-related data like modals, dropdowns, sidebar toggle, selected tabs, forms. Can often be managed with useState, Context API, or lightweight solutions. This separation improves: ✔ Performance ✔ Code maintainability ✔ Better developer experience ✔ Cleaner architecture In real-world frontend projects, choosing the right state management strategy matters more than just choosing a popular library. What are you currently using in your React projects for state management? Redux, Zustand, Context API, or React Query? 👇 #ReactJS #JavaScript #FrontendDevelopment #WebDevelopment #Redux #ReactQuery #SoftwareEngineering
To view or add a comment, sign in
-
-
🪝 The Secret Bookmark – Story of useRef in React Jay was building a form in React. He needed to auto-focus the input field when the page loaded. He tried useState... it re-rendered the whole component. 😩 He tried document.getElementById()... that felt wrong in React. 😕 Then his senior dev said: "Jay, use useRef." And everything changed. 🔥 ━━━━━━━━━━━━━━━ 💡 Meet useRef — React's direct line to the DOM: 💻 CODE =============== import { useRef } from "react"; function Form() { const inputRef = useRef(null); const handleClick = () => { inputRef.current.focus(); // direct DOM access! }; return ( <> <input ref={inputRef} type="text" /> <button onClick={handleClick}>Focus Input</button> </> ); } =============== 🧠 Simple understanding: useRef() gives you a box that holds a value. That value persists across renders — but changing it does NOT re-render. Two superpowers: → 🎯 Access DOM elements directly → 📦 Store values without triggering re-renders ━━━━━━━━━━━━━━━ ⚡ useRef vs useState — know the difference: 💻 CODE =============== // useState → triggers re-render on change const [count, setCount] = useState(0); // useRef → silently stores value, ➡️ no re-render const count = useRef(0); count.current = count.current + 1; =============== 🗂️ Real-world use cases: ✅ Auto-focus an input on page load ✅ Store previous state values ✅ Control video / audio play & pause ✅ Track render count without affecting UI ✅ Integrate with third-party DOM libraries ━━━━━━━━━━━━━━━ 🎬 Bonus — track renders silently: 💻 CODE =============== import { useRef, useEffect } from "react"; function App() { const renderCount = useRef(0); useEffect(() => { renderCount.current += 1; }); return <p>Rendered {renderCount.current} times</p>; // no infinite loop — ref change = no re-render! } =============== 📌 Think of useRef like a sticky note 🗒️ on your component: → You can write on it anytime → It stays there across renders → But React doesn't "see" it — so no re-render ━━━━━━━━━━━━━━━ 💬 "useState tells React to update the UI. useRef whispers to the DOM directly." If this cleared up your confusion about useRef, drop a 🔥 below! 📌 Save this — you'll need it in your next project. #React #useRef #ReactHooks #JavaScript #WebDevelopment #FrontendDevelopment #LearnToCode #ReactJS #Programming
To view or add a comment, sign in
-
-
🚀 Day 9 / 21 — Frontend Challenge Today I built: 👉 Weather App UI (Modern Dashboard Style) 🧠 Flow I designed before coding: • Designed layout structure (Header → Tabs → Cards → Forecast) • Created responsive UI with clean card-based design • Integrated free weather API (Open-Meteo) to fetch real-time data 🛠 Tech Used: HTML | CSS | JavaScript ✨ Features: • Real-time weather data (no API key required) • Clean modern UI with gradient background & glassmorphism cards • Hourly temperature preview with dynamic data 🚧 Challenges Faced: Handling API data flow and mapping it correctly to the UI was tricky, especially understanding how to first convert city name into coordinates and then fetch weather data. Also faced layout issues while removing unnecessary sections and restructuring the UI cleanly — solved it by simplifying grid structure and debugging step-by-step. 💡 Key Learning: Planning before coding makes development faster & cleaner 🙏 Guidance by: Keyur Gohil 🏫 Learning at:Red & White Skill Education Official 📂 GitHub Repo:https://lnkd.in/dXZbRGBn #21DaysJSWithKeyur #RedandWhite #Skill #JavaScript #FrontendDevelopment #BuildInPublic #WebDevelopment
To view or add a comment, sign in
-
🚀 Stop Dumping Everything in /src: The Blueprint for Production-Ready Frontend We've all been there: a project starts small, and suddenly your src folder is a graveyard of 50+ files with no clear home. The secret to a maintainable codebase isn't just the code you write-it's where you put it. A standardized folder structure like the one in this image is a gift to your future self (and your teammates). Why this specific setup works: 📂 api & services: Separation of concerns. Your api folder handles the raw Axios/Fetch calls, while services handles the logic of how that data is transformed for your Ul. 📂 components (ui vs. layout): Distinguishing between atomic Ul elements (buttons, inputs) and structural layouts (navbars, footers) makes finding components 10x faster. 📂 hooks & utils: If logic is used more than once, extract it. Custom hooks keep your components lean and focused on the view. 📂 context & redux: Clear boundaries for state management. Use context for global themes/auth and redux (or Zustand) for complex, data-heavy state. The "Scale" Test: Ask yourself: "If a new developer joined the team today, could they find the login API call in under 10 seconds?" If the answer is no, it might be time for a refactor. The Bottom Line: You don't build a house without a blueprint. Don't build an enterprise app without a structured directory. What does your "gold standard" frontend folder structure look like? Do you prefer "feature-based" folders or "type-based" ones? Let's debate in the comments! 👇 #webdevelopment #ReactJS #FrontendDevelooment #API #FullstackDevelopment
To view or add a comment, sign in
-
-
If there’s one thing I’ve learned while building out large-scale, modular applications, it’s that component bloat will quietly ruin your codebase. React components usually start small, but once you add data fetching, sorting, and state management, they become monstrous. I just published a new article on Medium breaking down my favorite solution to this: Custom Hooks. I explain the golden rule of clean React architecture—separating the "Brains" (logic) from the "Looks" (UI)—and how to actually implement it. If you want to write cleaner, more testable code, give it a read: "https://lnkd.in/gnZ44Hgu" #ReactJS #WebDevelopment #SoftwareArchitecture #CleanCode #FrontendDeveloper
To view or add a comment, sign in
-
🎯 Day 6 of 30: Conditional Rendering & Lists – The Logic Layer of React Today I unlocked the ability to make my UI "decide what to show" and "render collections from data" — two patterns every real‑world app depends on. 🧠 Core Patterns Mastered: 1️⃣ Conditional Rendering (The Four Patterns) - `&&` operator – show/hide an element without an else branch - Ternary `?:` – when you need an if/else UI state - Early return – guard clauses for loading, error, or empty states - Conditional styling – dynamic Tailwind/className toggles based on state 2️⃣ Rendering Lists with `.map()` - Transform arrays of data into arrays of JSX elements - Combine with "filter" to create dynamic, data‑driven UIs 3️⃣ The `key` Prop — Reconciliation & Stability - Keys must be "unique and stable" (item IDs, not array indexes) - React's diffing algorithm uses keys to efficiently update the DOM — wrong keys cause performance bugs and UI glitches 🛠️ Today's Builds: ✅ "TodoApp" – Full CRUD todo list with filter (All / Active / Done), conditional empty states, completed styling, and item count summary. Every todo has a stable `key` using `crypto.randomUUID()`. ✅ Accordion Component (Mini Build) – Single‑select FAQ accordion with `.map()`, conditional content rendering, and proper key management. ⚡ Key Insight: > "Don't render `0` accidentally." > When using `items.length && <Component />`, if the array is empty, React renders `0`. Always use `items.length > 0 && …` or a ternary. 📁 GitHub Commit Streak: Day 6 ✅ Every day's code is committed, documented, and pushed. Next: Day 7 – Week 1 Capstone Project! All concepts from the first week come together in a full‑featured Todo App that will be deployed live. #ReactJS #30DaysOfReact #WebDevelopment #Frontend #JavaScript #LearningInPublic #ReactLists #ConditionalRendering #CodeNewbie
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
-
-
Redux, Zustand, or just Context? Stop over-engineering your State Management. 🧠suit One of the most common mistakes I see in React development is reaching for a heavy state management library before it’s actually needed. As a Front-End Developer, my goal is to keep the architecture as simple as possible—but no simpler. In my Next.js projects, I follow a "Level-Up" approach to state: 1️⃣ Component State (useState / useReducer): If the data stays within one or two components, keep it local. Local state is easier to debug and keeps your components decoupled. 2️⃣ React Context: Perfect for "Static" global data that doesn't change frequently—like Theme modes (Dark/Light), User Authentication status, or Language settings. It’s built-in and powerful. 3️⃣ External Stores (Zustand / Redux ToolKit): When your state becomes "High-Frequency" (like a complex text editor or real-time dashboard) or your prop-drilling is out of control, that's when you bring in the heavy hitters. Personally, I'm loving Zustand lately for its zero-boilerplate approach. The best state management is the one that stays out of your way and doesn't kill your performance. What is your current go-to for global state in 2026? Are you still a Redux fan, or have you moved to simpler alternatives like Zustand or Jotai? Let's discuss! 👇 #ReactJS #StateManagement #Zustand #Redux #NextJS #WebDevelopment #CodingTips #FrontendArchitecture
To view or add a comment, sign in
-
-
I shipped a React dashboard with 40+ memoized components. The profiler was embarrassing. Here's what I found. Every component was wrapped in React.memo. Every callback was in useCallback. Every derived value was in useMemo. I thought I was being a good engineer. 𝗧𝗵𝗲 𝗽𝗿𝗼𝗳𝗶𝗹𝗲𝗿 𝘁𝗼𝗹𝗱 𝗮 𝗱𝗶𝗳𝗳𝗲𝗿𝗲𝗻𝘁 𝘀𝘁𝗼𝗿𝘆: → 200+ unnecessary renders per interaction → Memory allocation spiking on every keystroke → Frames dropping below 60fps during filter operations The irony? The memoization itself was causing the slowdown. Unstable object references being passed as deps. useCallback wrapping functions that didn't need stability. React.memo on components that rendered in 0.1ms anyway. Every "optimization" was a small tax. 40 components. Multiplied. I spent a day removing memo. Performance improved immediately. The lesson I took away: 𝗢𝗽𝘁𝗶𝗺𝗶𝘇𝗮𝘁𝗶𝗼𝗻 𝘄𝗶𝘁𝗵𝗼𝘂𝘁 𝗽𝗿𝗼𝗳𝗶𝗹𝗶𝗻𝗴 𝗶𝘀 𝗴𝘂𝗲𝘀𝘀𝗶𝗻𝗴. 𝗔𝗻𝗱 𝗰𝗼𝗻𝗳𝗶𝗱𝗲𝗻𝘁 𝗴𝘂𝗲𝘀𝘀𝗶𝗻𝗴 𝗶𝘀 𝘁𝗵𝗲 𝗺𝗼𝘀𝘁 𝗱𝗮𝗻𝗴𝗲𝗿𝗼𝘂𝘀 𝗸𝗶𝗻𝗱. Profile first. Memoize second. Only what the profiler tells you to. What React "best practice" did you have to unlearn? #React #Frontend #JavaScript #WebPerformance #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 Day 26/30 – useReducer (Advanced State Management) When state gets messy… "useState" starts struggling 👀 Today I learned how React handles complex state updates cleanly ⚡ 👉 useReducer --- 💻 The Problem: Managing multiple related states with "useState" ❌ 👉 Too many setters 👉 Scattered logic 👉 Hard to maintain --- 💻 The Solution: Use "useReducer" ✅ 👉 Centralize state logic in one place 👉 Predictable updates 👉 Easier to scale --- 💻 Example: import { useReducer } from "react"; const initialState = { count: 0 }; function reducer(state, action) { switch (action.type) { case "INCREMENT": return { count: state.count + 1 }; case "DECREMENT": return { count: state.count - 1 }; default: return state; } } function App() { const [state, dispatch] = useReducer(reducer, initialState); return ( <> <h2>{state.count}</h2> <button onClick={() => dispatch({ type: "INCREMENT" })}> + </button> <button onClick={() => dispatch({ type: "DECREMENT" })}> - </button> </> ); } --- 🔥 What actually happens: 1️⃣ User clicks button 2️⃣ dispatch(action) runs 3️⃣ reducer receives state + action 4️⃣ New state returned 5️⃣ UI updates --- 💡 Why this matters: ✅ Better for complex forms ✅ Multiple related states ✅ Cleaner update logic --- ⚡ Real Use Cases: - Shopping cart - Auth flow - Form wizard - Dashboard filters --- ⚡ Advanced Insight: "useReducer" is the same mental model used in Redux 👀 --- 🔥 Key Takeaway: Simple state → useState Complex state → useReducer --- Be honest 👇 Are you still forcing everything into useState? 🚀 #React #useReducer #FrontendDevelopment #JavaScript #StateManagement
To view or add a comment, sign in
-
More from this author
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