Designing Reusable Behavior in React with Custom Hooks ⚛️ Before custom hooks, every single page in my React app looked like this: useState for data. useState for loading. useState for error. useEffect to fetch. Axios call. Error handling. Toast on success. Invalidate cache manually. Multiply that by 30+ pages. That's hundreds of lines of repeated logic. So I stopped copy-pasting and started building. → useCustomQuery One hook. Every GET and POST request in the entire app. TanStack Query under the hood — caching, gcTime, pagination, enabled flag — all configurable. Pass the URL, method, and queryKey. Get clean data back. Zero boilerplate in the component. → useCustomMutation One hook. Every create, update, and delete operation. Automatic query invalidation after success. Toast notification fires itself. Modal closes itself. Session expiry triggers logout via Axios interceptor. The component calls mutate() and forgets about the rest. → useDebounceSearch 15 lines. Proper setTimeout cleanup.Configurable timer. Every search input in 30+ pages uses this one hook. Saves hundreds of unnecessary API calls every day.Search changes → skip resets to 0 automatically. The component just renders. It has no idea how any of it works. The result? ✦ Components went from 80 lines to 20 ✦ New pages now take half the time to build ✦ Bugs are isolated — fix once, fixed everywhere ✦ The entire team uses complex logic without understanding every detail Custom hooks didn't just clean up my code. They changed how I think about building React apps. Are you still writing the same logic in every component — or have you made the switch to custom hooks? #ReactJS #Frontend #JavaScript #TypeScript #WebDevelopment #CleanCode #SoftwareEngineering #FrontendDevelopment #ReactHooks #TanStackQuery
Reusable React Behavior with Custom Hooks
More Relevant Posts
-
Understanding Route Handlers in Next.js (App Router) Been working with the Next.js App Router recently, and one feature I think more developers should take advantage of is Route Handlers. They let you build backend logic directly inside your /app directory using the Web Request/Response APIs — no separate API routes needed. Here’s why they’re powerful: 🔵 1. Simple, file‑based backend logic Just drop a route.ts file anywhere inside /app: export async function GET(request: Request) {} Next.js automatically maps it to an API endpoint. Clean, predictable, and colocated with your UI. 🟠 2. Full support for HTTP methods GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS — all supported out of the box. If a method isn’t implemented, Next.js returns 405 Method Not Allowed automatically 🔵 3. Extended NextRequest & NextResponse You get helpers for cookies, headers, URL parsing, redirects, and more — perfect for auth, data validation, and secure server logic. 🟠 4. Smart caching behavior GET handlers can be cached using export const dynamic = 'force-static' Other methods always run dynamically Prerendering stops when you access runtime data (headers, cookies, DB queries, etc.) 🔵 5. Great for Backend‑for‑Frontend (BFF) patterns You can fetch external APIs, sanitize responses, enforce auth, and return exactly what your React components need — all inside the same route segment. Route Handlers feel like the missing piece between frontend and backend. They keep your logic close to your UI, reduce boilerplate, and make Next.js a true full‑stack framework. #Nextjs #ReactJS #WebDevelopment #FullStackDeveloper #JavaScript #TypeScript #APIDevelopment #BackendForFrontend #WebEngineering #CodingTips
To view or add a comment, sign in
-
🚀 Handling Token Expiry in React Apps using React Query (Modern Approach) 🔐 Tired of writing complex Axios interceptor logic everywhere? 🤯 There’s a cleaner and more scalable way 👇 --- 💡 Problem 👉 JWT token expires → APIs start failing with 401 👉 Handling this in every API = messy ❌ --- ⚡ Modern Solution 👉 Use React Query for global error handling 👉 Handle token expiry in one place 👉 Retry failed requests automatically --- 🔁 How It Works 1️⃣ API call via React Query 2️⃣ If 401 Unauthorized 3️⃣ Trigger refresh token API 4️⃣ Get new access token 5️⃣ Invalidate queries → auto retry ✅ --- 🧠 Why This is Powerful ✔ No repetitive error handling ✔ Built-in caching & retry ✔ Clean and scalable architecture ✔ Perfect for modern React apps --- 🔥 Interview Tip Instead of saying “I use Axios interceptors”… Say this 👇 💬 “I use React Query’s global error handling to manage token expiry. On 401 errors, I trigger a refresh token API and invalidate queries to retry them automatically. This keeps the code clean and avoids interceptor complexity.” --- ⚠️ Pro Tips 👉 Prevent multiple refresh calls using a flag 👉 Handle refresh failure → logout user 👉 Combine with secure storage (HttpOnly cookies 🔐) --- 🏆 When to Use ✔ Large-scale React apps ✔ Apps needing caching + performance ✔ Clean architecture lovers 😎 --- 💣 Final Takeaway 👉 “React Query simplifies token expiry handling by combining caching, retries, and global error handling in one place.” --- #ReactJS #ReactQuery #Frontend #JavaScript #JWT #WebDevelopment #SoftwareEngineering #InterviewPrep #CodingTips
To view or add a comment, sign in
-
🚀 How I eliminated redundant API calls in React (and improved performance) One common issue in React applications is unnecessary API calls, which can slow down the UI and increase backend load — especially in large-scale apps. Here’s what worked for me: ✅ Used a centralized data fetching strategy to fetch once and reuse across components ✅ Leveraged React Query / Redux / Context as a single source of truth ✅ Enabled caching and request deduplication to avoid repeated API calls ✅ Added conditional fetching (only call APIs when needed) ✅ Decoupled data fetching from UI components for better scalability 📈 Results: • Reduced redundant network requests • Faster page load times • Improved UI responsiveness • Better performance in data-heavy applications 💡 Key takeaway: Performance optimization isn’t just about rendering — it’s about how efficiently your application fetches and manages data. What strategies have you used to optimize API calls in React apps? #React #Frontend #WebDevelopment #Performance #JavaScript #NextJS
To view or add a comment, sign in
-
-
🚀 package.json vs package-lock.json in React (and any Node project) When you create a React app, you’ll always see two important files in the root folder: package.json and package-lock.json. They work together but have different roles. 1️⃣ package.json – “Project blueprint” Created manually or via npm init / create-react-app. Stores project metadata: name, version, scripts (like start, build, test). Lists dependencies and devDependencies with version ranges (e.g. ^18.2.0). This is the file you edit when you add, remove, or update packages. 2️⃣ package-lock.json – “Exact snapshot of dependencies” Auto-generated when you run npm install. You don’t edit it manually. Locks exact versions of every dependency and sub-dependency installed. Ensures everyone on the team (and CI/CD) installs the same versions, avoiding “works on my machine” issues. Also helps faster installs because npm doesn’t need to resolve versions again. 💡 In simple terms: package.json → What packages your React app needs. package-lock.json → The exact versions that were actually installed. ✅ Best practice: Commit both files to your repo. Edit package.json when changing dependencies and let npm manage package-lock.json automatically. #React #JavaScript #NodeJS #WebDevelopment #packagejson #packagelockjson #Angular
To view or add a comment, sign in
-
🚀 Mastering useState in React (Beyond the Basics) Most developers use useState. Very few actually master it. If you want to write scalable, high-performance React apps… this is where it starts 👇 ⚡ 1. Think in “State Transitions”, Not Variables useState is not just a variable — it represents a change over time. 👉 Always ask: What triggers this change? ⚡ 2. Use Functional Updates Like a Pro Avoid stale state bugs in async scenarios. ✅ setCount(prev => prev + 1) ⚡ 3. Keep State Minimal (Golden Rule) The more state you store → the more re-renders you create. 👉 Store only what you cannot derive. ⚡ 4. Split State for Better Performance Don’t dump everything into one object. ❌ Bad: const [state, setState] = useState({ name: '', age: 0 }) ✅ Better: const [name, setName] = useState('') const [age, setAge] = useState(0) ⚡ 5. Avoid Unnecessary Re-renders Every state update triggers a re-render. 👉 Optimize using: useMemo useCallback Component splitting ⚡ 6. Know When NOT to Use useState Not everything belongs in state. 👉 Use: useRef → for mutable values constants → for static data 💡 Real Mastery Insight: useState isn’t about managing data… It’s about controlling rendering behavior. 🔥 If you master this, your React code becomes: ✔ Cleaner ✔ Faster ✔ Production-ready 📌 Follow for advanced React + Full Stack insights. #ReactJS #FrontendDevelopment #ReactHooks #JavaScript #WebDevelopment #PerformanceOptimization #CodingTips #FullStackDevelopment #SoftwareEngineering #LearnReact
To view or add a comment, sign in
-
-
Most devs think Server Components vs Client Components is about "where code runs." That's technically true. But it misses the point. After 3 years of building React apps, here's the mental model that finally clicked for me: 🖥️ Server Components = Your Data Layer Think of them as the backend of your frontend. They run on the server, can access databases directly, and ship ZERO JavaScript to the browser. Use them when: → Fetching data (no more useEffect waterfalls) → Reading env variables or secrets → Rendering static/heavy layouts 💻 Client Components = Your Interaction Layer These are classic React. They hydrate in the browser and handle ALL interactivity. Use them when: → You need state (useState, useReducer) → You need lifecycle hooks (useEffect) → You need event handlers (onClick, onChange) The mistake everyone makes? Thinking "Server = fast, Client = slow." Wrong. Server Components reduce your bundle. Client Components cache beautifully. The power is in MIXING them — not choosing one. Here's the real-world pattern I use: 📂 Server Component (layout + data fetching) └─ 💻 Client Component (interactive form) └─ 🖥️ Server Component (search results) Nest them. Compose them. Stop treating them like enemies. The mental shift: Server Components are not "better React." They're a different tool for a different job. Once you get this, Next.js App Router finally makes sense. #React #NextJS #WebDev #Frontend #ServerComponents
To view or add a comment, sign in
-
-
CORS becomes very easy to understand with one real example. Imagine this: You’re building a React app on http://localhost:3000 Your backend API is running on http://localhost:8000 From your frontend, you make a request: fetch("http://localhost:8000/api/profile") Looks normal, right? But the browser sees this as: Frontend → localhost:3000 Backend → localhost:8000 Same machine. Same localhost. Different port. And that different port is enough for the browser to say: “Hold on — this is a different origin. I need permission first.” So before sending the real request, the browser asks your backend: “Is localhost:3000 allowed to access you?” That’s the CORS check. If your backend responds with: Access-Control-Allow-Origin: http://localhost:3000 The browser allows the request. If not, it blocks it and throws the CORS error. That’s why this fails: fetch("http://localhost:8000/api/profile") Not because your API is broken. Not because React failed. But because the browser is protecting the user. And that’s the key thing most beginners miss: CORS is not a server error. It’s the browser asking the server for permission. Once you understand that, CORS stops feeling random. #Frontend #WebDevelopment #JavaScript #ReactJS #NodeJS #FullStack #SoftwareEngineering #Developers #TechConcepts
To view or add a comment, sign in
-
-
What if you never had to build an API for your Laravel + Vue app? That's exactly what Inertia.js does. And in 2026, with v3 just released, it's better than ever. 🚀 Here's the idea: Instead of: Laravel API → CORS → token auth → Axios → state management → Vue You get: Laravel controller → Inertia → Vue component (as props) Your controllers return Inertia::render() instead of JSON. Vue components receive data as props. Laravel handles routing, auth, validation, and sessions — exactly as always. No duplication. No boilerplate. What Inertia v3 ships (March 2026): → No more Axios — built-in XHR client cuts ~15KB from your bundle → useHttp hook — reactive HTTP requests outside of page navigation (search, autocomplete) → Optimistic updates — instant UI changes with automatic rollback on error → SSR works in npm run dev — no more separate Node.js process during development → useLayoutProps — clean page-to-layout communication, no event bus needed And the features that were already amazing: ✔ useForm — Laravel validation errors mapped to fields automatically ✔ Shared data — auth user, flash messages available on every page ✔ Persistent layouts — sidebar never re-renders between navigations ✔ Inertia::optional() — lazy load expensive data only when needed I wrote the complete deep dive for installation to shared data, forms, persistent layouts, and when NOT to use Inertia. Are you already using Inertia.js? What stack are you pairing it with? #Laravel #InertiaJS #Vue #PHP #WebDevelopment #FullStack #100DaysOfBlogging
To view or add a comment, sign in
-
Most Node.js apps don't crash because of bad code. They crash because of bad error handling. Here's a pattern I use in almost every project: Instead of letting unhandled promise rejections silently kill your server, wrap your async route handlers in a reusable utility: const asyncHandler = (fn) => (req, res, next) => { Promise.resolve(fn(req, res, next)).catch(next); }; app.get('/user/:id', asyncHandler(async (req, res) => { const user = await getUserById(req.params.id); if (!user) throw new AppError('User not found', 404); res.json(user); })); app.use((err, req, res, next) => { res.status(err.status || 500).json({ message: err.message || 'Internal Server Error', }); }); That's it. One wrapper, one central error middleware, and your entire app handles errors consistently. The key insight: errors should flow to one place, not be scattered across every route with try/catch blocks copy-pasted everywhere. A custom AppError class lets you attach HTTP status codes and meaningful messages, so your API responses stay predictable for frontend teams. This also makes logging much easier — you intercept everything in one middleware and send it to whatever logging service you use. Small pattern, big payoff. Your teammates will thank you, and your on-call rotations will get a lot quieter. What's the error handling pattern you swear by in your Node.js projects — do you use something similar, or have you found a better approach? #nodejs #backend #javascript #softwaredevelopment #webdevelopment
To view or add a comment, sign in
-
-
Built a full-stack E-commerce Web Application using Node.js and Express.js, following the MVC (Model-View-Controller) architecture for scalability and maintainability. The system features a MySQL-based backend managing products, categories, users, and orders, along with secure authentication using bcrypt and session management. On the frontend, I used Pug to build dynamic server-side rendered pages, including an Admin Dashboard with full CRUD functionality. The application follows RESTful principles, utilizes middleware for authorization and request handling, and is structured with modular controllers, models, and routes for clean and maintainable code. GitHub project link: https://lnkd.in/dVThfiqy YouTube video: https://lnkd.in/d3iWuZWC #ecommerce #ai #mvc #web #webdevelopment #server #website #frontend #backend #project #software #javascript #nodejs #python #django #mysql #rest #api #wordpress #fullstack #ui #interface #admin #control
Shopping App using MVC & Template Engine with Node.js
https://www.youtube.com/
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