Simple React HOC Example Day8 🚀 React Tip: Higher-Order Component (HOC) Made Easy HOC = A function that takes a component and gives it extra features. Example: Button Click Counter import React, { useState } from "react"; // HOC to add counter const withCounter = (Component) => { return (props) => { const [count, setCount] = useState(0); return <Component count={count} increment={() => setCount(count + 1)} {...props} />; }; }; // Normal Button const LikeButton = ({ count, increment }) => ( <button onClick={increment}>👍 Likes: {count}</button> ); // Wrapped Button export default withCounter(LikeButton); ✅ Result: Button counts clicks automatically Logic reusable for other buttons No code repetition 💡 HOCs are useful for: Authentication 🔐 Error handling ❌ Reusable logic like counters or loaders 📈 #ReactJS #WebDevelopment #JavaScript #Frontend #ReactHOC
React HOC Example: Button Counter with Reusable Logic
More Relevant Posts
-
⚛️ In React, these three onClick patterns look almost identical… but behave very differently. onClick={handleAddItem} onClick={handleAddItem(item)} onClick={() => handleAddItem(item)} At a glance they seem similar, but the execution timing is completely different. 🔹 onClick={handleAddItem} Passes the function reference → runs only when the click event occurs. 🔹 onClick={handleAddItem(item)} Executes immediately during render, not on click. This can lead to unexpected behavior like unnecessary API calls or extra re-renders. 🔹 onClick={() => handleAddItem(item)} Creates a callback function that runs on click and allows you to pass parameters. ✅ Rule of thumb • No parameters → onClick={handleAddItem} • Need parameters → onClick={() => handleAddItem(item)} • Avoid → onClick={handleAddItem(item)} 💡 One more interesting detail Arrow functions create a new function on every render. In most cases this is perfectly fine. However, in large lists or memoized components (React.memo), this can sometimes trigger unnecessary re-renders. That’s why some developers use useCallback or pre-defined handlers for optimization. 👨💻 How do you usually handle this in your projects? Arrow functions, useCallback, or another pattern? #React #JavaScript #FrontendDevelopment
To view or add a comment, sign in
-
🔁 useCallback in React.js – Small Hook, Big Performance Impact When building React applications, unnecessary re-renders can silently affect performance. One hook that helps control this is useCallback. What is useCallback? useCallback is a React hook that memoizes a function, meaning React will reuse the same function reference between renders unless its dependencies change. This is especially useful when passing functions to child components, because React normally creates a new function on every render. That can cause child components to re-render even when nothing actually changed. Example: import { useState, useCallback } from "react"; function Counter() { const [count, setCount] = useState(0); const handleClick = useCallback(() => { console.log("Button clicked"); }, []); return ( <div> <button onClick={handleClick}>Click Me</button> <p>{count}</p> </div> ); } In this example, handleClick keeps the same function reference across renders because of useCallback. Why it matters: ✔ Prevents unnecessary re-renders ✔ Improves performance in optimized components ✔ Useful with React.memo When to use it? Use useCallback when: Passing functions to memoized components Working with expensive re-renders Optimizing large React applications ⚠️ But remember: Not every function needs useCallback. Overusing it can actually make code harder to maintain without real performance benefits. 💡 Understanding hooks like useCallback helps in writing cleaner and more optimized React applications. #ReactJS #WebDevelopment #JavaScript #FrontendDevelopment #ReactHooks #Coding
To view or add a comment, sign in
-
-
🤔 JavaScript Developers – What will be the output of this code? const p1 = new Promise((resolve, reject) => { setTimeout(() => resolve("p1 is success"), 1000); }); const p2 = new Promise((resolve, reject) => { setTimeout(() => reject("p2 is failed"), 5000); }); const p3 = new Promise((resolve, reject) => { setTimeout(() => resolve("p3 is success"), 4000); }); Promise.allSettled([p1, p2, p3]).then((res) => { console.log(res); }); 💬 Question: What do you think will be printed in the console? A️) [ { status: "fulfilled", value: "p1 is success" }, { status: "fulfilled", value: "p3 is success" } ] B️) [ { status: "fulfilled", value: "p1 is success" }, { status: "rejected", reason: "p2 is failed" }, { status: "fulfilled", value: "p3 is success" } ] C️) "p2 is failed" D️ Something else? 👇 Drop your answer in the comments. #JavaScript #Promises #FrontendDevelopment #ReactJS #WebDevelopment #Promise.allSettled
To view or add a comment, sign in
-
💡 React Tip: Use Custom Hooks to Reuse Logic One pattern I use frequently in React projects is custom hooks. Instead of repeating API logic across components, I move it into a reusable hook. Example 👇 function useFetch(url) { const [data, setData] = useState(null); useEffect(() => { fetch(url) .then(res => res.json()) .then(setData); }, [url]); return data; } Usage: const users = useFetch("/api/users"); Benefits: • Cleaner components • Reusable logic • Easier testing Custom hooks are one of the most powerful patterns in React. What’s your favourite custom hook? #ReactJS #FrontendDevelopment #JavaScript
To view or add a comment, sign in
-
🚀 Stop Using "Index" as a Key in Your Lists! Here’s Why. Ever wondered why React (or any modern UI framework) screams at you when you forget to add a key to a list? It’s not just a "coding rule"—it’s the secret sauce for performance and bug-free apps. Let’s break it down. 🧵 🔑 What is a "Key" anyway? Think of a list of items in your code like a coat check at a party. Without a tag (key), the attendant (React) has to look at every single coat to find yours. With a tag, they know exactly which one is yours instantly. A key is a unique identity. It helps the framework track which item was added, changed, or removed without re-rendering the entire list. 🚫 The "Index" Trap: Why key={index} is a bad idea We’ve all done it: items.map((item, index) => <li key={index}>...</li>). It stops the warning, but it creates a hidden bug. Here is the problem: Imagine you have a list of names: [0: "Alice", 1: "Bob", 2: "Charlie"]. If you delete "Alice," the list becomes: [0: "Bob", 1: "Charlie"]. Wait, what happened? "Bob" used to be index 1, but now he is index 0. React thinks index 0 just changed its text from "Alice" to "Bob." If you had a checkbox or a text input next to Alice, it might stay at index 0 and suddenly look like it belongs to Bob! Using an index is like identifying your friends by their "spot in line" rather than their "name." If someone leaves the line, everyone’s identity changes! ✅ The Golden Rule Always use a stable, unique ID from your data (like user.id or product.uuid). Better Performance: React only updates what actually changed. No UI Glitches: Your checkboxes, inputs, and animations stay attached to the right item. Happier Users: Smooth, fast, and bug-free interfaces. Keep your keys unique, keep your UI stable! 💻✨ #WebDevelopment #ReactJS #NextJS #Frontend #CodingTips #CleanCode #JavaScript
To view or add a comment, sign in
-
While working with React, I revisited something that looks small but has a huge architectural impact Keys vs Index in lists. At first, using index as a key feels harmless But here’s what actually happens under the hood 👇 React uses keys during the reconciliation process to decide Which component instance should be preserved Which one should be updated Which one should be removed Now imagine we delete an item from the middle Or reorder the list If we are using index as the key, React assumes the position defines identity. So instead of removing one component, it may re-use the wrong instance. Result? State shifts to the wrong item Input values jump unexpectedly Subtle UI bugs that are hard to debug That’s why a stable and unique key (like database id) is not just a best practice it’s about preserving component identity React isn’t diffing elements. It’s diffing identity. The more I revisit fundamentals, the more I realize: Great frontend development isn’t about writing code that works it’s about writing code that behaves correctly under change. #ReactJS #FrontendArchitecture #JavaScript #WebDevelopment #CleanCode #LearningJourney
To view or add a comment, sign in
-
🚀 Understanding Class Components in React One concept that helped me understand how components work internally was Class Components. Before Hooks became popular, class components were the primary way to manage state and lifecycle methods in React applications. A class component is simply a JavaScript class that extends React.Component and must contain a render() method that returns JSX. Example: import React, { Component } from "react"; class Welcome extends Component { render() { return <h1>Hello World</h1>; } } export default Welcome; In class components: 🔹 Props are accessed using this.props 🔹 State is managed using this.state 🔹 State updates are done with this.setState() 🔹 Lifecycle methods like componentDidMount() allow us to run code when the component mounts, updates, or unmounts. Example with state: class Counter extends Component { state = { count: 0 }; increase = () => { this.setState({ count: this.state.count + 1 }); }; render() { return ( <button onClick={this.increase}> {this.state.count} </button> ); } } Today, most developers prefer Functional Components with Hooks like useState and useEffect, but understanding Class Components is still valuable because: ✅ Many legacy React projects still use them ✅ They help you understand React's lifecycle deeply ✅ Some interview questions still cover them Learning both approaches gives you a stronger foundation in React. Sometimes, understanding the old way helps you appreciate the modern way even more. #React #FrontendDevelopment #JavaScript #WebDevelopment #LearningInPublic
To view or add a comment, sign in
-
Ever found yourself chaining .filter().map() and thought, "There must be a cleaner way"? 🤔 If you're working with arrays in JavaScript, you probably use .map() every day. But what if you need to turn one item into multiple elements, or skip some items entirely without creating an ugly nested array? That’s where .flatMap() becomes your best friend. As a React dev, I used to struggle with rendering logic when one data point needed to produce two components (like a Label and a Divider). Check out the difference: const items = ['React', 'Next.js']; ❌ The old way (creates nested arrays) items.map(item => [item, 'Separator']); Result: [['React', 'Separator'], ['Next.js', 'Separator']] - React hates this! ✅ The flatMap way (flattens as it maps) items.flatMap(item => [item, 'Separator']); Result: ['React', 'Separator', 'Next.js', 'Separator'] - Clean & flat! Why I love using it in React: * Conditional Rendering: Instead of filtering first and then mapping, you can just return an empty array [] for items you want to skip. It's cleaner and more performant because you only iterate once. * Cleaner JSX: No more fragmented arrays or weird index % 2 logic to insert dividers between list items. * Performance: It combines two operations (map + flat) into a single pass. Next time you're about to chain .filter().map(), try reaching for .flatMap() instead. Your code (and your future self) will thank you. How often do you use flatMap in your projects? Let me know in the comments! 👇 #JavaScript #WebDevelopment #ReactJS #CodingTips #CleanCode #Frontend
To view or add a comment, sign in
-
-
🚀 React Performance Tip: Lazy Loading One of the most effective ways to improve performance in React applications is Lazy Loading. Instead of loading the entire JavaScript bundle at once, React allows us to load components only when they are needed. This technique is widely used in large-scale applications to improve user experience and reduce initial load time. 🔹 Common Lazy Loading Use Cases: 1️⃣ Lazy loading components 2️⃣ Lazy loading routes with React Router 3️⃣ Lazy loading images for faster page rendering 4️⃣ Loading heavy libraries only when required Example: const Profile = React.lazy(() => import("./Profile")); <Suspense fallback={<div>Loading...</div>}> <Profile /> </Suspense> 💡 Benefits: ✔ Faster initial page load ✔ Smaller bundle size ✔ Better performance ✔ Improved user experience Lazy loading is a must-know optimization technique for modern frontend developers, especially when building large React applications. Are you using lazy loading in your projects? 👇 #ReactJS #FrontendDevelopment #WebPerformance #JavaScript #CodeSplitting #ReactDeveloper #SoftwareEngineering #WebDevelopment #Programming #FrontendEngineer
To view or add a comment, sign in
-
-
React Hooks: useState vs useRef — Know the Difference When working with React functional components, two commonly used hooks are useState and useRef. While they may seem similar at first, they serve different purposes. -- useState * Used to store and manage component state * When the state updates, React re-renders the component * Ideal for data that affects the UI Example: const [count, setCount] = useState(0); -- useRef * Used to store mutable values that persist across renders * Updating a ref does NOT trigger a re-render * Commonly used for accessing DOM elements or storing previous values Example: const inputRef = useRef(null); -- Simple Rule to Remember: * If the value affects the UI → useState * If the value should persist but not trigger re-render → useRef Mastering these hooks helps you write cleaner and more efficient React components. #ReactJS #WebDevelopment #FrontendDevelopment #JavaScript #ReactHooks #SoftwareDevelopment
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