⚛️ A small React concept that makes a big difference — Custom Hooks Ever noticed how Components start getting messy when they handle too much state or logic? ✅ Api Calls ✅ Toggles ✅ Timers ✅ Scroll or Resize Listeners ✅ Form Logic Instead of repeating the same code everywhere, just extract it into a Custom hook. Cleaner components, Reusable logic, Fewer bugs. e.g.: function useToggle(initial = false) { const [value, setValue] = useState(initial); const toggle = () => setValue(v => !v); return [value, toggle]; } // const [open, toggleOpen] = useToggle(); Suddenly your component becomes lighter, readable, and scalable. You can combine multiple hooks and get a polished UI without clutter. If you're a beginner: ➡️ Learn custom hooks early ➡️ Your future self will thank you What’s the coolest custom hook you’ve built or used recently? 🚀 #reactjs #javascript #frontend #webdev #reacthooks #cleancode #programmingtips #buildinpublic
How to Clean Up Your React Components with Custom Hooks
More Relevant Posts
-
Custom Hooks in React 🔁 If you’ve worked with React, you already know how powerful built-in hooks like useState and useEffect are. But the real magic begins when you start creating your own custom hooks. Custom hooks allow developers to extract and reuse logic across different components. Instead of repeating the same logic in multiple places, you can simply wrap it inside a custom hook — keeping your code clean, modular, and easier to maintain. 💡 Why use Custom Hooks? Reuse complex logic across components Keep components focused purely on UI Improve readability and scalability Simplify debugging and testing For example, you could create custom hooks for things like API fetching, managing authentication, handling dark mode, or tracking window size. In short, custom hooks bring structure and reusability to your React applications — turning repetitive patterns into elegant, maintainable code. #React #WebDevelopment #Frontend #JavaScript #Coding #Hooks #CustomHooks #TechLearning #ReactJS #stemup
To view or add a comment, sign in
-
⚛️ React Just Made Form Actions Way Cleaner React’s new hook — useActionState — is a game-changer for handling async form submissions. No more juggling useState, useEffect, or endless try/catch blocks. 🙌 Here’s what it does 👇 🧩 You pass it: A form action (e.g., addToCart) An initial state It gives you back three things: 1️⃣ The latest state (e.g., message or result) 2️⃣ A wrapped action (formAction) 3️⃣ A flag showing if it’s still running (isPending) Now your form logic becomes simpler, more declarative, and easier to read. Just write the action, hook it up, and React handles the rest. It’s a small addition but one that makes a big difference in building clean, async-ready UIs. ⚡ 💬 Have you tried useActionState yet? What’s your take on React’s direction with these new declarative patterns? #ReactJS #JavaScript #WebDevelopment #Frontend #ReactHooks #CleanCode #AsyncProgramming #DeveloperExperience #SoftwareEngineering #CodingTips #ReactDevelopers #DevCommunity #UIUX
To view or add a comment, sign in
-
-
React 19.2 just dropped a new <𝗔𝗰𝘁𝗶𝘃𝗶𝘁𝘆> component. Let’s explore what it can do: <𝗔𝗰𝘁𝗶𝘃𝗶𝘁𝘆> is a React component that lets you 𝗵𝗶𝗱𝗲/𝘀𝗵𝗼𝘄 UI components while 𝗽𝗿𝗲𝘀𝗲𝗿𝘃𝗶𝗻𝗴 𝘁𝗵𝗲𝗶𝗿 𝗶𝗻𝘁𝗲𝗿𝗻𝗮𝗹 𝘀𝘁𝗮𝘁𝗲. Instead of completely unmounting components (which destroys their state), it uses 𝗱𝗶𝘀𝗽𝗹𝗮𝘆: 𝗻𝗼𝗻𝗲 to hide them. 𝗞𝗲𝘆 𝗙𝗲𝗮𝘁𝘂𝗿𝗲𝘀: 𝟭. 𝗦𝘁𝗮𝘁𝗲 𝗣𝗿𝗲𝘀𝗲𝗿𝘃𝗮𝘁𝗶𝗼𝗻: When hidden, components keep their React state (like form inputs, expanded sections, etc.) 𝟮. 𝗗𝗢𝗠 𝗣𝗿𝗲𝘀𝗲𝗿𝘃𝗮𝘁𝗶𝗼𝗻: The actual DOM elements stay in the tree, so things like video timecodes or textarea content are maintained 𝟯. 𝗘𝗳𝗳𝗲𝗰𝘁 𝗖𝗹𝗲𝗮𝗻𝘂𝗽: Hidden components have their Effects cleaned up (no active subscriptions), but Effects restart when shown again 𝟰. 𝗣𝗿𝗲-𝗿𝗲𝗻𝗱𝗲𝗿𝗶𝗻𝗴: Hidden components can pre-render at low priority to speed up future interactions 𝗕𝗮𝘀𝗶𝗰 𝗨𝘀𝗮𝗴𝗲: <Activity mode={isVisible ? "visible" : "hidden"}> <MyComponent /> </Activity> 𝗠𝗮𝗶𝗻 𝗨𝘀𝗲 𝗖𝗮𝘀𝗲𝘀: 1. Tab interfaces - Keep form data when switching tabs 2. Sidebars - Preserve expanded/collapsed state 3. Pre-loading - Render heavy components in background 4. Performance - Improve hydration by splitting component tree 𝗜𝗺𝗽𝗼𝗿𝘁𝗮𝗻𝘁 𝗡𝗼𝘁𝗲𝘀: - Hidden components still re-render (at lower priority) - Effects are cleaned up when hidden, restarted when shown - DOM side effects (like playing videos) persist unless you add cleanup - Works great with Suspense for data fetching 𝗖𝗼𝗺𝗺𝗼𝗻 𝗚𝗼𝘁𝗰𝗵𝗮: If you have DOM elements with side effects (video, audio, iframe), you need to add cleanup Effects to pause them when hidden: useLayoutEffect(() => { return () => videoRef.current.pause(); }, []); It's basically a smarter way to show/hide components. #Nextjs #Reactjs #ReactNative #JavaScript #WebDevelopment #Frontend #FullStack #TypeScript #Programming #Tech #SoftwareEngineer #DevCommunity
To view or add a comment, sign in
-
-
SolidJS: why developers are calling it the “React killer” SolidJS offers reactivity without a Virtual DOM and near-zero overhead. Core benefits: Fine-grained reactivity → faster than React’s reconciliation. Simple syntax similar to React → easy learning curve. Backed by real-world production apps and growing ecosystem. Solid isn’t a hype — it’s the natural evolution of declarative UIs. Source: https://lnkd.in/e-Vb2_6f #SolidJS #Frontend #JavaScript #Performance #WebDevelopment
To view or add a comment, sign in
-
🪝 Custom Hooks, Power, but with Discipline At some point, every React dev writes a custom hook. It starts with a simple useFetch or useForm, and before you know it, you’re managing your own mini framework. 😅 Over time, I’ve learned that creating custom hooks is less about code reuse and more about clarity. Here’s what I’ve found works best 👇 💡 When Custom Hooks Make Sense ✅ You want to extract repeated logic used across components. ✅ You’re handling complex state or side effects that clutter UI components. ✅ You need a clear abstraction layer between logic and presentation. ⚠️ When They Don’t 🚫 You’re creating a hook to “make it look cleaner.” 🚫 The hook ends up being used only once, and makes debugging harder. 🚫 You’re wrapping libraries (like React Query or Zustand) for no real reason. A good rule of thumb: “If your hook makes code simpler for the next person, keep it. If it hides clarity, rethink it.” What’s the most useful custom hook you’ve written recently? 👇 #ReactJS #TypeScript #FrontendDevelopment #CleanCode #SoftwareEngineering #ReactHooks #WebDev #VipinYadav
To view or add a comment, sign in
-
-
⚛️ Understanding `useState` Updates in React: Why They Seem Asynchronous and How to Handle It In React, `useState` is the most common way to manage state in functional components. But one thing that often confuses developers is that state updates via `setState` don’t happen immediately — they are batched and applied during the next render. This makes `useState` seem asynchronous. What’s really happening? • Calling `setState` schedules an update, but doesn’t instantly change the state variable. • On the current render, reading the state variable right after `setState` still gives the old value. • React batches multiple `setState` calls for performance and applies them together before the next render. Example of the issue: const [count, setCount] = useState(0); const increment = () => { setCount(count + 1); console.log(count); // Logs old value, not updated one }; Clicking increment multiple times may not behave as expected because `count` inside the function is “stale” due to closure capturing the old value. How to safely update state based on the current value Use the functional update form of `setState`, which guarantees you get the latest state: setCount((prevCount) => prevCount + 1); This avoids stale closures and works well even if multiple updates happen quickly. Need to respond to state changes? Use `useEffect` to act when state changes: useEffect(() => { console.log('Count updated:', count); }, [count]); Key Takeaway • `setState` itself is synchronous internally, but React batches updates and re-renders asynchronously. • Don’t rely on updated state immediately after calling `setState` in the same render cycle. • Use functional updates and `useEffect` for reliable, up-to-date state management. Mastering this behavior is essential for avoiding bugs and writing predictable React components. #ReactJS #JavaScript #FrontendDevelopment #Hooks #WebDev
To view or add a comment, sign in
-
-
💭 Ever wished window.confirm() could show your own custom modal? I did — and got tired of juggling modal states, callbacks, and context just to ask: “Are you sure?” So I built a small helper for myself… and figured others might find it useful too 👇 👉 @sghere/react-confirm A minimal, promise-based confirm utility for React — lightweight, zero-config, and works beautifully with your own UI. ✨ Features 🧩 Zero configuration — works out of the box ⚛️ Fully compatible with React 16+ and 18 💬 Promise-based API: await confirm({...}) 🧠 Type-safe with ConfirmOptions support 🎨 Tailwind-ready styling — easily themeable 🪶 Lightweight — under 5 KB gzipped 📦 Installation npm install @sghere/react-confirm # or yarn add @sghere/react-confirm # or bun add @sghere/react-confirm ⚠️ Requires react and react-dom as peer dependencies 🚀 Quick Start import { confirm } from "@sghere/react-confirm"; import "@sghere/react-confirm/dist/react-confirm.css"; <button onClick={() => { confirm({ heading: "Are you sure?", body: "This will be deleted", onConfirm: () => { alert("Deleted ✅"); }, }); }} > Delete Item </button> It’s a small utility — nothing fancy — but it’s made my workflow cleaner and faster. If you give it a try, I’d love your thoughts or suggestions to make it better 🙌 #React #OpenSource #Frontend #JavaScript #ReactJS #WebDev #DeveloperTools #DevCommunity
To view or add a comment, sign in
-
-
If you hide a component using {isVisible && <Component />}, React removes it from the tree, so you lose its state. If you hide it with CSS (display: none), it stays mounted, meaning timers and effects keep running, which hurts performance. Now with <Activity />, React offers a smarter approach: The UI is hidden. The component’s state remains intact. Background work (timers, subscriptions, etc.) is automatically paused. 👉 Think of it like browser tabs — when you switch tabs, the inactive one pauses but keeps its data safe, so when you return, it picks up right where you left off. ⚡ Perfect for: • Tabbed interfaces • Multi-step forms • Complex UIs where hidden parts should pause, not reset #React #ReactJS #ReactDevelopers #WebDevelopment #Frontend #FrontendDevelopment #JavaScript #Coding #Programming #WebDev #SoftwareEngineering #UIUX #CodeTips #DevCommunity #CleanCode #WebDesign #TechTips #DeveloperLife #ReactHooks #ReactComponents
To view or add a comment, sign in
-
-
Daily Dev Tip: Boost your JavaScript and React skills with small, repeatable habits. Today's focus: break complex UI into small, reusable components and lift state up when it makes the data flow clearer. In React, prefer functional components and hooks over classes, use useEffect for side effects, and consider useCallback/useMemo to optimize expensive computations. Try a tiny, daily practice: build a component in 15 minutes and refactor twice this week. Share your best tip in the comments! #JavaScript #React #WebDevelopment #Frontend
To view or add a comment, sign in
-
I love this clean folder structure for this #NextJS project! The src/features/dashboard-group/ setup organizes shared components, utilities, and dashboard-specific logic, making code easy to maintain and helping new devs jump in fast. What folder structures do you use to keep your #Frontend projects organized? Share your tips! #CleanCodeSolutions #WebDevelopment #Frontend #React #JavaScript #NextJS
To view or add a comment, sign in
-
Explore related topics
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
If you want me to create more detailed and discuss concepts in depth, do provide your feedback.