🚀 7 React Hooks Every Front-End Developer Should Know (with examples) When I first started learning React, hooks felt confusing. 🤯 But once I understood them, my components became cleaner, more powerful, and easier to manage. If you’re learning React, these 7 hooks are absolute must-knows 👇 ⸻ 🔹 1️⃣ useState — Manage component state Used to store and update data inside a component. Example: import { useState } from "react"; function Counter() { const [count, setCount] = useState(0); return ( <button onClick={() => setCount(count + 1)}> Count: {count} </button> ); } 💡 Common uses • counters • form inputs • toggle buttons ⸻ 🔹 2️⃣ useEffect — Handle side effects Runs code when a component loads or updates. Example (API call): import { useEffect, useState } from "react"; function Users() { const [users, setUsers] = useState([]); useEffect(() => { fetch("https://lnkd.in/g9ryQvzH") .then(res => res.json()) .then(data => setUsers(data)); }, []); return <div>{users.length} users loaded</div>; } 💡 Common uses • API requests • fetching data • event listeners • timers ⸻ 🔹 3️⃣ useContext — Share global data Avoids passing props through many components. Example: import { createContext, useContext } from "react"; const ThemeContext = createContext("light"); function Header() { const theme = useContext(ThemeContext); return <div>Theme: {theme}</div>; } 💡 Great for • dark / light theme 🌙 • authentication 👤 • global settings ⚙️ ⸻ 🔹 4️⃣ useRef — Access DOM elements Used to directly interact with elements. Example: import { useRef } from "react"; function InputFocus() { const inputRef = useRef(); return ( <> <input ref={inputRef} /> <button onClick={() => inputRef.current.focus()}> Focus Input </button> </> ); } 💡 Common uses • focusing inputs • animations • storing previous values ⸻ 🔹 5️⃣ useMemo — Optimize performance Prevents unnecessary recalculations. Example: import { useMemo } from "react"; const result = useMemo(() => { return expensiveCalculation(data); }, [data]); 💡 Useful for • filtering large lists • heavy calculations • performance optimization ⸻ 🔹 6️⃣ useCallback — Prevent unnecessary re-renders Memoizes functions passed to child components. Example: import { useCallback } from "react"; const handleClick = useCallback(() => { console.log("Button clicked"); }, []); ⸻ 🔹 7️⃣ useReducer — Manage complex state Great when state logic becomes complicated. Example: import { useReducer } from "react"; function reducer(state, action) { switch (action.type) { case "increment": return { count: state.count + 1 }; default: return state; } } const [state, dispatch] = useReducer(reducer, { count: 0 }); 💡 Perfect for • complex forms • large applications • structured state management #React #FrontendDeveloper #JavaScript #WebDevelopment #CodingJourney
7 Essential React Hooks for Front-End Developers
More Relevant Posts
-
Why TypeScript + React in 2026 Is the Best Developer Experience You're Not Fully Using TypeScript adoption in React projects just hit 78% (State of JS 2025). But here's the uncomfortable truth: most teams are still using 2022 patterns—and missing out on what makes this stack genuinely magical today. Here's what changed and why it matters: 1. No More `import React from 'react'` The new JSX transform means cleaner files. Just update your `tsconfig.json`: ```json "jsx": "react-jsx" ``` Your components now look like actual JavaScript, not React-wrapped code. 2. Stop Using `React.FC` It's 2026. We've moved on. // Old const Card: React.FC<CardProps> = ({ title, children }) => {} // 2026 interface CardProps { title: string; children?: React.ReactNode; } const Card = ({ title, children }: CardProps) => {} Explicit > implicit. Always. 3. Generic Components Are Shockingly Simple Full type inference with zero effort: const List = <T,>({ items, renderItem }: ListProps<T>) => { ... } Your IDE now knows exactly what `item` is inside `renderItem`. No more `any` cheating. 4. Discriminated Unions for Bulletproof State No more impossible states: type State = | { status: 'loading' } | { status: 'success'; data: User[] } | { status: 'error'; error: string }; TypeScript forces you to handle every case. Your users will never see "undefined is not a function" again. 5. Type Your Hooks Like a Pro Custom hooks deserve first-class types: const useLocalStorage = <T,>(key: string, initial: T) => { return [value, setValue] as const; // Tuple inference }; 6. Strict Mode Isn't Optional Enable these in `tsconfig.json` or you're leaving safety on the table: - `strict: true` - `noUncheckedIndexedAccess` (catches those pesky array bugs) - `exactOptionalPropertyTypes` Quick Wins You Can Implement Today - `interface` over `type` for props (better error messages) - `as const` for readonly literals - `satisfies` operator to validate without widening - Zod + TypeScript for runtime validation The Bottom Line TypeScript + React in 2026 isn't just about catching bugs—it's about building with confidence. The patterns have settled, the tooling is rock-solid, and the community has aligned around what actually works at scale. Your future self (and your team) will thank you. What's the one TypeScript pattern you couldn't live without? #TypeScript #ReactJS #WebDevelopment #Programming
To view or add a comment, sign in
-
🚀 Starting Journey into Server-Side JavaScript with Node.js : After taking a short break from frontend development, I started diving into the Node.js ecosystem over the past few days. Here are some foundational concepts I’ve been learning about server-side JavaScript and REST APIs. 🔹 Node.js? Node.js allows JavaScript to run on the server, enabling developers to build full-stack applications using a single programming language. Key characteristics: • Asynchronous & Event-Driven Architecture – Handles multiple requests efficiently using non-blocking I/O • High Scalability – Suitable for building fast, network-based applications • npm Ecosystem – Access to thousands of open-source packages • Efficient Backend Development – Ideal for APIs, microservices, and real-time apps 🔹 Client-Side vs Server-Side JavaScript Client-Side JavaScript : 1. Runs in the browser 2. Handles UI interactions and dynamic content 3. Improves user experience Server-Side JavaScript (Node.js) 1. Runs on the server 2. Processes requests and business logic 3. Generates dynamic responses for clients Both communicate through web services using JSON over HTTP, allowing seamless data exchange between frontend and backend. 🔹 Building a Simple REST API with Node.js & Express A basic REST service typically follows these steps: 1️⃣ Setup Project npm init npm install express 2️⃣ Create Basic Server const express = require('express'); const app = express(); const PORT = 3000; app.use(express.json()); app.listen(PORT, () => { console.log(`Server running on http://localhost:${PORT}`); }); 3️⃣ Define RESTful Routes (CRUD) let items = []; // GET app.get('/items', (req, res) => { res.json(items); }); // POST app.post('/items', (req, res) => { const newItem = req.body; items.push(newItem); res.status(201).json(newItem); }); // PUT app.put('/items/:id', (req, res) => { const { id } = req.params; items[id] = req.body; res.json(req.body); }); // DELETE app.delete('/items/:id', (req, res) => { const { id } = req.params; items.splice(id, 1); res.status(204).send(); }); It’s exciting to see how JavaScript can power both the frontend and backend of modern applications. Next up: Database integration and Middleware! Any tips for a Node.js beginner? 👌👉 #NodeJS #WebDevelopment #Backend #JavaScript #LearningInPublic #CodingJourney
To view or add a comment, sign in
-
**10 useful TypeScript tricks** . TypeScript has become a core part of modern React development. Beyond basic typing, it provides powerful utilities that make code **safer, cleaner, and more maintainable**. 1️⃣ `Partial<T>` – Optional Properties Useful for update forms or API patches. interface User { id: number name: string email: string } type UpdateUser = Partial<User> -------------- 2️⃣ `Pick<T, K>` – Select Specific Fields type UserPreview = Pick<User, "id" | "name"> Great when a component only needs **specific data**. ------------- 3️⃣ `Omit<T, K>` – Remove Fields type PublicUser = Omit<User, "email"> Useful for hiding **private fields**. ----------------- 4️⃣ `Readonly<T>` – Immutable Data const user: Readonly<User> = { id: 1, name: "John", email: "john@example.com" } Prevents accidental state mutation. -------------- 5️⃣ `Record<K, T>` – Dynamic Object Types type Roles = Record<string, string> const userRoles: Roles = { admin: "full access", editor: "edit content" } -------------- 6️⃣ `keyof` – Extract Object Keys type UserKeys = keyof User Result: "id" | "name" | "email" -------------- 7️⃣ `typeof` – Infer Types from Variables const user = { id: 1, name: "Abeer" } type UserType = typeof user --------------- 8️⃣ `as const` – Literal Types const status = ["loading", "success", "error"] as const Now TypeScript knows the exact values. ------------- 9️⃣ Generics Reusable type-safe functions. function identity<T>(value: T): T { return value } --------------- 🔟 Union Types type Status = "loading" | "success" | "error" 💡 **Why this matters** Using TypeScript effectively helps: ✔ Prevent runtime bugs ✔ Improve code readability ✔ Build scalable React applications What’s your favourite TypeScript feature ?
To view or add a comment, sign in
-
⚠️ React developers: Your dropdown isn't broken. Your DOM tree is lying to you. Being a full-stack developer means you're basically a one-person circus — frontend, backend, auth flows, DB schema, API contracts, real-time sync, pagination logic, timezone handling, and about 47 other things before your first coffee. And then... a dropdown misbehaves. You've set z-index: 9999. You're on Tailwind's z-50. You've stared at the DevTools inspector like it owes you money. And that dropdown is still hiding behind a card, a modal, or some random parent wrapper. Here's what's actually going on — and it's not your fault. The real culprit: CSS Stacking Contexts When a parent element carries overflow: hidden, transform, opacity < 1, or will-change, it silently creates a new stacking context. Your z-index is now scoped within that parent only — not the full document. So z-index: 9999 inside a transformed card still loses to z-index: 1 outside it. You're not fighting the dropdown. You're fighting the DOM tree itself. The fix that actually holds up: React Portal dropdown.jsx file - import ReactDOM from 'react-dom'; const Dropdown = ({ children, style }) => { return ReactDOM.createPortal( <div style={style}>{children}</div>, document.body ); }; createPortal() renders your dropdown directly at document.body completely outside every parent's stacking context. No more overflow battles. No more z-index wars. But here's the catch nobody mentions: Since the dropdown is now detached from its trigger element, you have to manually position it. Use getBoundingClientRect() on the trigger button to calculate exact top/left coordinates and inject them as inline styles. Don't skip this step or your dropdown will haunt the top-left corner of the screen. This is how modals, tooltips, and production-grade dropdowns are built. This is the kind of thing no tutorial warns you about. You only discover it at 11 PM when everything else is done and this one tiny thing refuses to fall in line. 🧠 Lesson Not every bug is about syntax. Some are about understanding how the browser actually works. And that’s the difference between: fixing issues randomly vs solving them once and for all If this saved you a late-night debugging session — pass it on..... 📌 MDN — https://lnkd.in/dD5HU5ZB 📌 React Docs — https://lnkd.in/dJB8NW7R 📌 Deep dive on z-index & stacking — https://lnkd.in/dCVgYX45 #ReactJS #FullStackDev #WebDevelopment #FrontendEngineering #TailwindCSS #ReactPortal #JavaScriptTips #UIEngineering #CSSDeepDive #BuildInPublic
To view or add a comment, sign in
-
-
Arc is a web framework I built from scratch using Node.js and TypeScript. Most people just use Express, but I wanted to build my own engine so I could control every single step of how a request is handled. It doesn't use any libraries if a request comes in, I wrote the code that catches it. What I built from scratch? 1. The URL Matching System (The Router) : I didn't use a pre made router iwrote a system that uses Regular Expressions to read URLs. If I make a route like /users/:id, my code turns that into a search pattern. It can pull out the ID (like 77 or user-abc) automatically and give it to the rest of the code. It is flexible and doesn’t break easily with special characters. 2. The step by step Chain (The Pipeline) : I built a "pipeline" where every request has to pass through specific checkpoints (Middlewares) before it finishes. I used a recursive next() function this means the server starts one task (like checking a login), and only when that is 100% finished does it move to the next task. This keeps the server very stable it prevents "race conditions" where two different parts of the code try to talk to the user at the same time. 3. Custom Request & Response Tools : The basic tools that come with Node.js are very "raw" and hard to use i wrapped them to make them better. 4- The JSON Parser: I wrote my own code to read incoming data it’s built to be safe so that if someone sends a massive, fake file, it won't crash the server's memory. 5- Easy Commands: I added simple ways to send data back, like res.json() and res.status(). It makes the code much cleaner and easier to read. 6. The Safety Net (Error Boundary) Usually, if a server has a tiny typo in the code, the whole thing crashes and stays offline i built a Global Safety Net. I wrapped the whole engine in a try/catch block. If one route has a bug, the server catches the error, sends a "500 Error" message to that user, and stays running for everyone else. How to help me improve it? The core is done, but I need help making it production-ready I'm looking for people to help with: 1- Speed Tests: Finding out where the URL matcher slows down when there are thousands of requests. 2- Database Connection: Finding the cleanest way to plug in databases like PostgreSQL or Redis. 3- Security: Adding more built in shields against hackers (like XSS or CSRF protection). 4- Cleanup: Making the core code even smaller and faster. If you like building things from the ground up and seeing exactly how a web server works under the hood, I'd love to have you help me improve Arc. Github : https://lnkd.in/dfmwM_Cb
To view or add a comment, sign in
-
-
Understanding the architecture behind a tech stack is just as important as writing the code. I’ve recently been exploring the inner workings of the MERN stack—how React, Node.js, Express, and MongoDB collaborate to create seamless full-stack experiences. I decided to document my findings in a beginner-friendly guide to help others visualize the data flow and server logic. If you’re looking to solidify your understanding of full-stack development, I’d love for you to check it out and share your thoughts! Read the full article on Hashnode: https://lnkd.in/gKzTFM5P #WebDevelopment #MERNStack #SoftwareEngineering #JavaScript #FullStackDeveloper #LearningToCode
To view or add a comment, sign in
-
⚛️ Blazor vs React — A Practical Comparison for .NET FullStack Developers As a .NET FullStack developer when building modern web applications: Both are powerful component-based frameworks, but they differ in ecosystem, programming model, and tooling. If we're a .NET developer exploring frontend options, here’s a side-by-side comparison of key concepts 🔹 Component-Based Architecture Blazor → Razor Components (.razor files) Uses C# and Razor syntax to build reusable UI components. React → Functional / Class Components (.jsx / .tsx) Uses JavaScript/TypeScript with JSX to create reusable UI components. 🔹 Parent → Child Communication Blazor → [Parameter] properties Parents pass data to children via parameters. React → props Parents pass data to children through props. Both follow a unidirectional data flow. 🔹 Child → Parent Communication Blazor → EventCallback<T> Child components notify parents through event callbacks. React → Callback functions via props Child components call functions passed from parents. 🔹 State Management Blazor Component state Cascading parameters Dependency Injection services State container pattern React useState useReducer Context API External libraries (Redux, Zustand, Recoil) 🔹 Component Lifecycle Blazor OnInitialized() OnParametersSet() OnAfterRender() Dispose() React Functional components with hooks: useEffect() useLayoutEffect() (Class components use componentDidMount, componentDidUpdate, etc.) 🔹 Hooks vs Reactive Logic Blazor Reactive rendering built into the component model State change automatically triggers UI updates No direct equivalent of hooks React Hooks provide reusable logic: useState useEffect useContext useMemo useCallback 🔹 Dependency Injection Blazor Built-in DI support similar to ASP.NET Core. Example: @inject WeatherService WeatherService React Uses Context API or third-party libraries for dependency management. 🔹 Routing Blazor @page "/products" Routing defined directly inside components. React Handled using React Router. 🔹 Forms & Validation Blazor EditForm DataAnnotationsValidator Model binding React Controlled components Libraries like Formik or React Hook Form 🔹 API Communication Blazor Uses HttpClient with strongly typed models. React Uses fetch, axios, or data libraries like React Query / SWR. 🔹 Rendering Model Blazor Blazor Server (SignalR connection) Blazor WebAssembly (runs in browser via WebAssembly) React Client-side rendering Server-side rendering with Next.js 🔹 Language Ecosystem Blazor C# .NET ecosystem Shared models between backend and frontend React JavaScript / TypeScript Massive open-source ecosystem 💡 When to Choose Blazor ✔ Strong .NET ecosystem ✔ Full-stack C# development ✔ Enterprise applications ✔ Shared code between backend and frontend 💡 When to Choose React ✔ Large ecosystem and community ✔ Rich frontend tooling ✔ Highly interactive UI applications ✔ Easier hiring in large teams #dotnet #blazor #reactjs #webdevelopment #softwareengineering #frontend #fullstack
To view or add a comment, sign in
-
🚀 Why useRef in React Can Make Your Life as a Developer Much Easier If you've been working with React for a while, you probably rely heavily on useState and useEffect. They are the backbone of most React applications. But there is another hook that many developers overlook or only use occasionally: useRef. At first glance, useRef might seem simple or even unnecessary. However, once you truly understand its power, it can significantly improve performance, simplify logic, and help you avoid unnecessary re-renders. Let’s talk about why useRef can become one of your favorite tools as a React developer. 1️⃣ Avoiding Unnecessary Re-renders One of the most practical benefits of useRef is that it allows you to store values without triggering a component re-render. When you use useState, every update causes React to re-render the component. Sometimes this is exactly what you want — but sometimes it isn't. For example, if you just need to store a value temporarily (like a timer ID, previous value, or scroll position), using useState can cause unnecessary rendering cycles. With useRef, you can store the value like this: const timerRef = useRef(null); timerRef.current = setTimeout(() => { console.log("Timer finished"); }, 2000); The component won't re-render when timerRef.current changes, which makes your application more efficient. 2️⃣ Direct Access to DOM Elements Another common use case for useRef is accessing DOM elements directly. React usually encourages declarative programming, but sometimes you need to interact directly with the DOM — focusing an input field, measuring an element, or controlling scrolling. Example: const inputRef = useRef(null); const focusInput = () => { inputRef.current.focus(); }; return ( <> <input ref={inputRef} /> <button onClick={focusInput}>Focus Input</button> </> ); This is clean, simple, and avoids complicated workarounds. 3️⃣ Persisting Values Between Renders A very interesting feature of useRef is that its value persists between renders. This means you can use it to keep track of previous values or store information that should survive across component updates. Example: storing the previous state. const prevValue = useRef(); useEffect(() => { prevValue.current = value; }, [value]); This is incredibly useful when building things like: - custom hooks - performance optimizations - tracking previous props or states 😄 useRef might look like a small tool in the React ecosystem, but it solves very real problems developers face every day. Once you start using it intentionally, you'll notice improvements in: - performance - code clarity - control over component behavior So next time you're about to create a new piece of state, pause for a moment and ask yourself: "Do I really need a re-render here?" If the answer is no, useRef might be exactly what you need.
To view or add a comment, sign in
-
-
At the start of the year, I decided to take my programming more seriously by building and showcasing a project every month, no matter how big or small. This month, I completely rebuilt The Log Book (refer to last month's post). It is a developer focused, note taking app to log coding insights, bugs, and ideas. The aim was to transform my original vanilla JS/Node.js version into a production ready full-stack application with proper architecture and user authentication. Building on that foundation, I decided to improve the code. I aimed to implement the following: Express.js + Mongoose – Migrate from vanilla Node.js for cleaner routing and proper data modeling User Authentication – Complete auth system with registration, secure login, and user-specific private notes Email Notifications – Welcome emails, login alerts, and note confirmations using Nodemailer React Frontend – Rebuild the UI with protected routes and real-time motivational messages Backend deployed on Render – Separate from the frontend, at it is better for backends because it runs persistent Node.js servers Getting emails working turned into its own challenge. Gmail + Nodemailer worked perfectly locally, then died on Render (they block SMTP ports on free tier). Hours of debugging later, I switched to Resend's API. Resend worked great, until I discovered the free tier only lets you email yourself. To actually notify users, you need a verified domain, which means buying one. So after building an entire full-stack app for free, I'm stuck at the last step: spending money to finish the job (which I wasn't willing to do)😅. Regardless, I'm still very proud of this project. Another major challenge was Cross Origin Resource Sharing (CORS). Deploying the frontend on Vercel and backend on Render worked really well initially, until I spent two days fighting CORS errors and disappearing session cookies. This is because browsers have difficulties sharing login data between different domains. After way too many late nights tweaking same site attributes and trust proxy settings, I finally got it. Users now have private accounts and persistent cloud storage which for me, is a huge step forward. And I am excited to share it. 💻 GitHub: [https://lnkd.in/dQXVQTfj] 🚀 Live: [https://lnkd.in/dCaPM-Hm] 🎥 Demo video attached #NodeJS #ExpressJS #MongoDB #React #Authentication #WebDevelopment #CodingJourney
To view or add a comment, sign in
-
⚙️ Backend Development with Node.js — How Modern Applications Work When developers talk about full-stack applications, the backend is where the real logic happens. And one of the most powerful backend technologies today is Node.js. It allows developers to build fast, scalable server-side applications using JavaScript. 🔹 What is Node.js? Node.js is a JavaScript runtime environment that runs outside the browser. Instead of only building frontend interfaces, developers can now use JavaScript to build: ✔ Servers ✔ APIs ✔ Real-time applications ✔ Microservices ✔ Full backend systems This is why JavaScript became a full-stack programming language. 🔹 Why Developers Love Node.js Node.js has become one of the most popular backend technologies because it offers: ✔ High performance ✔ Non-blocking architecture ✔ Large ecosystem of libraries ✔ Same language for frontend and backend This makes development faster and more efficient. 🔹 How Backend Works with Node.js In a modern application, the backend usually performs tasks like: • Handling user authentication • Processing business logic • Communicating with databases • Managing APIs • Sending responses to the frontend When a user interacts with the UI, the request goes to the backend server built with Node.js. The server processes the request and returns data to the frontend. 🔹 Node.js in the MERN Stack Node.js is a key part of the popular MERN stack: Frontend → React Backend → Node.js Server Framework → Express.js Database → MongoDB This stack allows developers to build complete full-stack applications using JavaScript. 🔹 Real-World Applications Built with Node.js Node.js powers many modern applications such as: • APIs for web and mobile apps • Real-time chat applications • Streaming platforms • SaaS dashboards • Microservice architectures Its speed and scalability make it ideal for high-traffic applications. 💡 Pro Developer Insight One of the biggest advantages of Node.js is using the same language across the entire stack. This means developers can build: Frontend → React Backend → Node.js APIs → Express Database → MongoDB All using JavaScript. 🎯 Final Thought Backend development is the engine behind every modern application. And Node.js has become one of the most powerful tools for building fast, scalable, full-stack systems. If you understand Node.js, you unlock the ability to build complete production-level applications. #NodeJS #BackendDevelopment #MERNStack #JavaScript #FullStackDeveloper #WebDevelopment #SoftwareEngineering
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