7 React Hooks You Must Master React Hooks replaced class components and changed how every React developer thinks about state, side effects, and performance. Master these 7 and you can handle 95 percent of React challenges. -> useState Your component's memory. Stores local state and triggers a re-render when it changes. The most used hook in React by a significant margin. -> useEffect Handles everything that happens outside the render cycle. API calls, subscriptions, timers, and DOM manipulation all live here. Runs after every render unless you control its dependency array. -> useContext Access global state without passing props through every level of the component tree. Works perfectly with the Context API for theme, auth, and shared configuration. -> useRef Two jobs: access DOM elements directly without a re-render, and store values that persist across renders without causing re-renders. More powerful than most developers realize when they first learn it. -> useMemo Memorizes the result of an expensive calculation. Only recalculates when its dependencies change. Use it when a computation is genuinely expensive and runs on every render. -> useCallback Memorizes a function reference between renders. When you pass a callback to a child component, useCallback prevents the child from re-rendering because it receives a new function reference every render. -> useReducer Complex state logic that involves multiple sub-values or state transitions that depend on the previous state. Think of it as a mini Redux built directly into React. More predictable than multiple useState calls for complex state. These seven hooks cover state management, side effects, performance optimization, and DOM interaction. Everything else in React builds on these foundations. Which of these seven do you use least and think you should probably use more? #React #ReactHooks #FrontendDevelopment #JavaScript #WebDevelopment #Developers
Mastering React: 7 Essential Hooks for State Management and Performance
More Relevant Posts
-
Understanding why a component re-renders in React, even when it seems nothing has changed, is crucial for optimizing performance. In the example of the Parent component, we have: ```javascript function Parent() { const [count, setCount] = useState(0); const handleClick = () => { console.log("Clicked"); }; return <Child onClick={handleClick} />; } ``` Even when the Child component is wrapped with React.memo, it still re-renders. The reason is that functions in JavaScript are re-created on every render. Therefore, on each render, `handleClick` is not equal to the previous `handleClick`, leading React to perceive it as a new prop. As a result, the Child component receives a new function reference, prompting React to think the props have changed, which causes the Child to re-render. To prevent this, we can use `useCallback` to memoize the function: ```javascript const handleClick = useCallback(() => { console.log("Clicked"); }, []); ``` This way, React retains the same function reference between renders. Key Insight: React compares references, not function logic. However, it's important to note that `useCallback` should not be overused. It is best utilized when: - Passing functions to child components - Optimizing performance with React.memo #ReactJS #JavaScript #FrontendDevelopment #WebDevelopment #SoftwareEngineering #CodingJourney #LearninglnPublic #DeveloperLife #ReactInternals #FrontendEngineer #TechInterview #StateManagement #ReactHooks
To view or add a comment, sign in
-
A very common React mistake I see developers make: Mutating State When I was learning React, one concept that changed the way I write code was this rule: 👉 React state must never be mutated.its always immutable. But why? React does not deeply compare objects or arrays when state updates. Instead, it performs a reference(memory) comparison. That means React checks: Old State === New State ? If the reference is the same, React assumes nothing changed and skips re-rendering. Example of a mistake: cart.push(product) // ❌ Mutating state setCart(cart) Here we modified the same array in memory, so React may not detect the change because the memory location is same.so no re-render..no UI update. The correct approach is immutability: setCart([...cart, product]) // ✅ Creating a new array Now React sees a new reference, triggers reconciliation, and updates the UI correctly. 💡 Why React prefers immutability: • Faster change detection • Predictable state updates • Easier debugging • Better performance This small concept explains why patterns like: map() filter() spread operator (...) are used so frequently in React. because all this returns new object or array... Understanding this helped me write cleaner and more reliable React components. What React concept took you the longest to understand? 🤔 #React #Frontend #JavaScript #WebDevelopment #ReactJS
To view or add a comment, sign in
-
-
How I Learned to Optimize 100k+ Items in React One day I built a simple list in React. Everything was fine… until I loaded 100,000+ items 😅 Suddenly: • UI became slow • Scrolling lagged • My laptop fan started acting like a jet engine ✈️ I thought: 👉 “React is slow.” But I was wrong. 🧠 Then I asked a better question 👉 Do users really need to see 100,000 items at once? The answer was obvious: ❌ No. Users only see what’s on the screen. 💡 That’s when it clicked Instead of rendering everything, I should render only visible items. This concept is called: 👉 Virtualization 🧠 Human version of this Imagine a long book 📖 You don’t read all pages at once. You only read the current page. Same idea. 🚀 What I changed Instead of: ❌ Rendering 100k items I did: ✅ Render only 20–30 visible items ✅ Load more as user scrolls 🔧 Tools that helped me • react-window • react-virtualized These libraries handle everything smartly. ⚡ Extra optimizations I learned • Use useMemo for heavy calculations • Use useCallback for stable functions • Avoid unnecessary re-renders • Keep components lightweight 💡 The biggest lesson Performance is not about doing more. It’s about doing less… smartly. Now whenever my app slows down, I ask: 👉 Am I rendering more than needed? Still learning React the human way. 🚀 #JavaScript #FrontendDevelopment #LearningInPublic #CleanCode #ReactJS #FrontendDevelopment #LearningInPublic #JavaScript #WebDevelopment #DeveloperJourney #ReactHook #Performance
To view or add a comment, sign in
-
-
You think this React code will increment the counter to 2? Maga Look again.👇🐘🐘🐘 function App() { const [count, setCount] = useState(0); const handleClick = () => { setTimeout(() => { setCount(count + 1); }, 1000); setCount(count + 1); }; return ( <> <p>{count}</p> <button onClick={handleClick}>Click</button> </> ); } Most developers say: 👉 “First +1 immediately, then +1 after 1 second → final = 2” ❌ Wrong 🧠 What actually happens setCount(count + 1) → updates to 1 setTimeout callback runs later… But it uses stale count = 0 (closure!) 👉 So it sets 1 again 🎯 Final Result Count = 1, not 2 🚨 The real problem This is not a React bug This is a JavaScript closure + event loop problem Functions capture old state Async callbacks don’t magically get updated values React state is snapshot-based, not live ✅ Fix setCount(prev => prev + 1); ✔ Always use functional updates when state depends on previous value ✔ Works correctly with async (timeouts, promises, events) 💡 Takeaway If your mental model is: 👉 “state updates automatically everywhere” You’ll ship bugs. If your mental model is: 👉 “state is captured at execution time” You’ll write predictable systems. This is the difference between writing code that works… and code that scales in production. USE prev maga 😍 setCount(prev => prev + 1); 🐘🐘🐘 #ReactJS #JavaScript #Frontend #WebDevelopment #Debugging #EventLoop
To view or add a comment, sign in
-
React vs. Redux vs. Redux Toolkit: Which should you use? "Do I need Redux?" is still one of the most common questions in frontend development. State management can be overwhelming, but understanding the evolution of these tools makes the choice much clearer. Here is a straightforward breakdown of the big three: 1️⃣ React State & Context (The Foundation) React’s built-in hooks (useState, useReducer, useContext) are often all you need. The Good: Zero extra dependencies. It is perfect for local component state (like form inputs or UI toggles) and low-frequency global state (like user themes or auth status). The Bad: Relying purely on Context for high-frequency, complex global state can lead to unnecessary re-renders and messy prop-drilling. 2️⃣ Classic Redux (The Legacy Heavyweight) Redux revolutionized how we handle global state by introducing a single, predictable source of truth. The Good: Unmatched predictability and incredible developer tools (time-travel debugging is magic). The Bad: The boilerplate. Writing separate files for actions, action types, and reducers slows down development and frustrates teams. 3️⃣ Redux Toolkit / RTK (The Modern Standard) Redux Toolkit is not a replacement for Redux; it is the official, modern way to write it. It takes everything great about Redux and strips away the pain points. The Good: It drastically reduces boilerplate. Features like createSlice automatically generate your actions and reducers. It includes Immer under the hood (allowing you to write simpler, "mutating" logic that updates state immutably), and it ships with RTK Query for incredibly efficient data fetching and caching. The Verdict: If you are starting a new project that genuinely needs Redux, RTK is the only way you should be writing it. 💡 My Rule of Thumb: Start simple. Build with React's built-in state. When your state starts feeling tangled, difficult to track, or requires passing props through five layers of components (Prop Drilling)—it's time to bring in Redux Toolkit. How is your team handling state management these days? Are you firmly on team RTK, or have you pivoted to lighter alternatives like Zustand or Jotai? Let's discuss in the comments! 👇 #ReactJS #Redux #WebDevelopment #Frontend #SoftwareEngineering #JavaScript
To view or add a comment, sign in
-
-
⚛️ React Tip: When Should You Use useCallback? While working on React applications, one common performance issue developers face is unnecessary component re-renders. One hook that often comes up in this discussion is useCallback. But many developers (including me earlier) either overuse it or use it incorrectly. So here’s a simple way to understand it. 🔹 What does useCallback do? `useCallback` memoizes a function. This means React will reuse the same function instance unless its dependencies change. Example 👇 const handleClick = useCallback(() => { console.log("Button clicked"); }, []); Without `useCallback`, a new function is created every time the component re-renders. Most of the time this isn’t a problem. But it becomes important when passing functions to memoized child components. 🔹 Example scenario Imagine a parent component passing a function as a prop to a child component wrapped with `React.memo`. If the function reference changes on every render, the child component will also re-render unnecessarily. Using `useCallback` helps keep the function reference stable, preventing those extra renders. 🔹 When should you actually use it? ✅ When passing callbacks to memoized components ✅ When the function is a dependency in another hook ✅ When optimizing large component trees ⚠️ When NOT to use it: • For every function in your component • When there is no performance issue • Just because someone said it improves performance 💡 One important lesson I’ve learned: Optimization should be intentional, not automatic. React already does a lot of work under the hood. Use hooks like `useCallback` only when they actually solve a problem. Curious to hear from other developers 👇 Do you use `useCallback` often, or do you prefer optimizing only after profiling? #reactjs #frontenddevelopment #javascript #webdevelopment #reacthooks #softwareengineering #coding
To view or add a comment, sign in
-
-
Day 13: Component Lifecycle in React (Using Hooks) Before Hooks, React had lifecycle methods in class components. Now, with Hooks, we can handle the entire lifecycle using useEffect. 📌 What is Component Lifecycle? Every React component goes through 3 main phases: 1️⃣ Mounting → Component is created and added to the DOM 2️⃣ Updating → Component re-renders when state/props change 3️⃣ Unmounting → Component is removed from the DOM 📌 Handling Lifecycle with useEffect 👉 1. Mounting (Component Did Mount) useEffect(() => { console.log("Component Mounted"); }, []); Runs only once when the component loads. 👉 2. Updating (Component Did Update) useEffect(() => { console.log("Component Updated"); }, [count]); Runs whenever count changes. 👉 3. Unmounting (Component Will Unmount) useEffect(() => { return () => { console.log("Component Unmounted"); }; }, []); Used for cleanup (like clearing timers, removing listeners). 📌 Real-world Example Think of a timer app • Start timer → Mount • Update time → Update • Stop/leave page → Unmount 📌 Why Lifecycle is Important ✅ Prevent memory leaks ✅ Manage API calls properly ✅ Control when code runs ✅ Optimize performance #ReactJS #FrontendDevelopment #JavaScript #WebDevelopment #CodingJourney #LearnInPublic
To view or add a comment, sign in
-
⚛️ 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
-
What Runs First in React? Most React developers know what useEffect, useMemo, and useCallback do individually. Far fewer know the exact order they execute in. And that gap causes bugs that are surprisingly difficult to trace. Here is the definitive execution order on first mount: -> Step 1: Rendering JSX React runs the function body of your component first. JSX is evaluated. console.log inside the return runs here. This is the render phase. -> Step 2: useMemo runs during render useMemo executes synchronously during the render phase, not after it. If you have an expensive computation wrapped in useMemo, it runs as part of building the component output. This is why useMemo can be used to compute values that are needed in the JSX itself. -> Step 3: useEffect runs after render After the component has rendered and the DOM has been updated, useEffect fires. It is intentionally deferred. This is where API calls, subscriptions, and side effects belong because they should not block the render. -> useCallback is different from all of them useCallback does not run during mounting. It stores a function reference. That function only executes when it is explicitly called. In the example on the right, increment only logs when you actually call increment(). The final order: Rendering JSX, then useMemo, then useEffect. Why this matters in practice: If you expect useEffect to run before useMemo, your state update will not be available when useMemo computes. If you expect useCallback to run automatically, your side effect will never fire. Getting the order wrong means working with stale data and writing code that behaves differently than you intended. Understanding execution order is not academic. It is the difference between components that behave predictably and ones that produce subtle timing bugs you spend hours debugging. Did you know the exact execution order before seeing this or did it surprise you? #React #ReactHooks #FrontendDevelopment #JavaScript #WebDevelopment #Developers
To view or add a comment, sign in
-
-
🚀 Day 12/30 – Conditional Rendering in React Building dynamic UIs based on conditions ⚡ Today’s focus was on Conditional Rendering — a core concept that makes React apps interactive and user-driven. 🔍 What I learned: ✅ Conditional Rendering allows UI to change based on state ✅ React relies on pure JavaScript logic (if, ternary, &&) inside JSX ✅ Essential for real-world features like authentication, loaders, and error handling 💻 Example: function App() { const isLoggedIn = true; return ( <> {isLoggedIn ? <h1>Welcome User</h1> : <h1>Please Login</h1>} </> ); } 🔥 Common Patterns: 1️⃣ Ternary Operator (Most Used) {condition ? <A /> : <B />} 2️⃣ Logical AND (&&) {isLoggedIn && <Dashboard />} 3️⃣ If Statement (Outside JSX) if (!user) return <Login />; 💡 Real-World Use Cases: ✔️ Showing a loader while fetching data ✔️ Displaying error messages ✔️ Rendering dashboard after login ⚡ Advanced Insight: React doesn’t introduce new syntax for conditions — it simply leverages JavaScript inside JSX, making it flexible and powerful. 🔑 Key Takeaway: 👉 Conditional Rendering = Controlling what users see based on application state. 💬 Curious — which approach do you use more: ternary or if/else logic? #React #FrontendDevelopment #JavaScript #WebDevelopment #LearningInPublic
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