Why can’t we create a state variable outside the component function? const [count, setCount] = React.useState(0); ❌ function Counter() { return <div>{count}</div>; } function Counter() { const [count, setCount] = React.useState(0); ✅ return <div>{count}</div>; } Why? Because Hooks rely on the component’s render cycle. When React renders a component, it: 1️⃣ Calls the component function 2️⃣ Tracks the order of Hooks 3️⃣ Stores state internally based on that order Hooks are tightly connected to the component’s lifecycle. If you declare state outside: ❌ There is no render context ❌ No component lifecycle ❌ React can’t track it #ReactJS #ReactHooks #ReactInternals #FrontendDevelopment #JavaScript #SoftwareEngineering #WebDevelopment #LearningInPublic #ReactInterview #FrontendEngineer #TechInterview
React Hooks State Variable Placement
More Relevant Posts
-
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
-
How React Remembers State Between Renders? When a component re-renders, the function runs again from top to bottom. So how does useState not reset every time? 🤔 function Counter() { const [count, setCount] = React.useState(0); return <button onClick={() => setCount(count + 1)}>{count}</button>; } Every render: The function runs again and Variables are recreated. So why doesn’t count go back to 0? What Actually Happens Internally React stores state outside the component function. Behind the scenes: 1) Each component has a Fiber node 2) React keeps a linked list of Hooks 3) It tracks Hooks based on call order State is not stored in your function. It’s stored in React’s internal Fiber system. The function is just a way for React to describe UI. Understanding this makes Hooks feel much less magical. #ReactJS #ReactInternals #ReactHooks #FrontendDevelopment #SoftwareEngineering #JavaScript
To view or add a comment, sign in
-
-
Today while building a pagination component in React, I came across the use of Array.from() in JavaScript. The problem I was facing was simple: I wanted to show page numbers between the Previous and Next buttons. For example: Prev 1 2 3 4 5 Next At first, I was thinking about how to generate those numbers dynamically instead of writing them manually. That’s when I came across Array.from(). It helped me create an array of a specific length and then generate page numbers from it. Something like this: Array.from({ length: totalPages }, (_, i) => i + 1) This creates: [1, 2, 3, 4, 5] Which can then be mapped easily to render pagination buttons in React. A small thing, but it made pagination logic feel much cleaner and more dynamic. Am I understanding this correctly? Would love to know if there’s a better or more practical way you usually handle pagination numbers. #JavaScript #ReactJS #WebDevelopment #Frontend #Pagination
To view or add a comment, sign in
-
-
Why is your useEffect sitting idle even after you've updated the variable? Look at this snippet. If you’re coming from a Vanilla JS background, count = count + 1 looks perfectly fine. But in React? This code is technically "dead." Why this won't work: * Mutation != Re-render: You are updating a local let variable. React has no "spy" watching your local variables. Unless you call a state setter (like setCount), React doesn't know it needs to re-render the component. * The Lifecycle Gap: useEffect only checks its dependency array ([count]) when the component re-renders. Since the button click doesn't trigger a render, React thinks nothing has changed. * The "Reset" Trap: Even if the component did re-render for some other reason, the first line let count = 0; would run again, resetting your value back to zero every single time. The Fix? Stop treating React like a standard script. Use useState. When you use const [count, setCount] = useState(0), you’re telling React: "Hey, keep an eye on this value. If I change it via setCount, please refresh the UI and check my Effects." Pro-tip: In React, if you want the UI to "react," you have to use the Hook. Simple as that. #ReactJS #WebDevelopment #Frontend #CodingTips #IndiaDevs #Javascript
To view or add a comment, sign in
-
-
💡 React Tip: Why Functional Components Are the Standard Today When I started working with React, class components were widely used. But over time, functional components have become the preferred approach — especially with the introduction of React Hooks. Here are a few reasons why developers prefer functional components today: ✅ Cleaner and simpler code – Less boilerplate compared to class components ✅ Hooks support – Hooks like useState, useEffect, and useMemo make state and lifecycle management easier ✅ Better readability – Logic can be grouped by functionality instead of lifecycle methods ✅ Improved performance optimization – Tools like React.memo and hooks make optimization easier Example: function Counter() { const [count, setCount] = React.useState(0); return ( <button onClick={() => setCount(count + 1)}> Count: {count} </button> ); } Functional components combined with Hooks make React development more scalable, maintainable, and easier to reason about. 📌 Curious to know from other developers: Do you still use class components in production projects, or have you fully moved to functional components? #ReactJS #FrontendDevelopment #JavaScript #WebDevelopment #ReactHooks
To view or add a comment, sign in
-
Another core concept in React is props, short for “properties.” Props are how data moves from one component to another. Think of them as inputs you pass into a component so it can display or use that data. For example, you might have a reusable component that displays a user card. Instead of hardcoding the name or email inside the component, you pass that information in as props. The component stays flexible, and you can reuse it in different places with different data. This pattern is what makes React applications easier to organize. Small components receive data through props, render what they need, and stay focused on a single job. Once you start thinking in terms of components passing data through props, building larger interfaces becomes much more manageable. #reactjs #webdevelopment #frontenddevelopment #javascript #softwaredevelopment
To view or add a comment, sign in
-
-
Today something interesting happened while I was building a Custom Date Picker in NextJS.🗓 I have used useRef many times before, but honestly I was mostly using it without fully understanding the concept behind it But today… it finally clicked.💫 While implementing the feature, I realized that: • useRef creates a mutable object • The value is stored inside .current • The value persists between renders • Updating .current does not trigger a re-render • It can also be used to directly access DOM elements The most interesting part for me was understanding why React doesn't re-render when current changes. Sometimes you don’t truly understand a concept until you build something real with it. Small learning today, but a very satisfying one. 💫 What was the React concept that took you the longest to understand❓️ #React #JavaScript #FrontendDevelopment #ReactHooks #BuildInPublic #LearningJourney
To view or add a comment, sign in
-
Today I learned about the useRef hook in React, and it’s actually very useful! What is useRef? It allows us to create a reference that persists across renders without causing re-renders. Key Uses: Access DOM elements directly Store mutable values without re-rendering Useful for focus, timers, and previous values Example: import { useRef } from "react"; function InputFocus() { const inputRef = useRef(null); const handleClick = () => { inputRef.current.focus(); }; return ( <> <input ref={inputRef} type="text" /> <button onClick={handleClick}>Focus Input</button> </> ); } What I learned: Unlike state, updating useRef does NOT trigger a re-render. Excited to explore more React hooks! #ReactJS #FrontendDevelopment #WebDevelopment #JavaScript #LearningInPublic #90DaysOfCode
To view or add a comment, sign in
-
𝗔 𝗦𝘂𝗯𝘁𝗹𝗲 𝗥𝗲𝗮𝗰𝘁 𝗕𝘂𝗴 𝗖𝗮𝘂𝘀𝗲𝗱 𝗯𝘆 𝗦𝘁𝗮𝗹𝗲 𝗦𝘁𝗮𝘁𝗲 Sometimes a bug in React isn’t caused by React itself. It comes from how JavaScript closures work. When you schedule a state update inside an asynchronous callback (like a timeout), that callback captures the value of state from the moment it was created. If the state changes before the callback runs, the update may still use the old value. This can lead to confusing behavior where your UI doesn’t update the way you expect. A safer approach is to use the functional update pattern. Instead of relying on the current state value, React gives you the latest state inside the updater function. This ensures your update always works with the most recent value. 👇 Example comparison below Day 13/100 — sharing practical frontend engineering lessons. Have you ever faced a bug caused by stale state in React? #ReactJS #FrontendEngineering #JavaScript #WebDevelopment #SoftwareEngineering
To view or add a comment, sign in
-
-
Just built a Login Page using React — and honestly, useState made it so clean! 🚀 The whole toggle between Sign In and Sign Up? Just one boolean state and a setFunction doing all the heavy lifting. ```jsx const [isSignIn, setIsSignIn] = useState(true); ``` No extra libraries. No complexity. Just props flowing down and a setter function flipping the view. It's one of those moments where React just *clicks* — you realize how powerful a single state value can be when your components are built right. If you're learning React, start here. Build a login page. Toggle two views with useState. You'll understand props and state faster than any tutorial. 💡 #React #ReactJS #useState #FrontendDevelopment #WebDevelopment #JavaScript #100DaysOfCode
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
Great breakdown Sajal! 👏 You're totally right about useState. Just a fun addition: keeping state outside the component is actually exactly what tools like Zustand do! It’s a lifesaver for avoiding crazy re-renders and prop drilling when the app scales up. So sometimes that ❌ is actually a ✅!