🚀 Controlled vs Uncontrolled Components in React When handling forms in React, we often use either Controlled or Uncontrolled components. The difference is about who manages the input data. 🔵 Controlled Component A controlled component is an input field whose value is managed by React state. 👉React becomes the single source of truth. Example: import { useState } from "react"; function ControlledForm() { const [name, setName] = useState(""); return ( <input type="text" value={name} onChange={(e) => setName(e.target.value)} /> ); } Here ●'useState' stores the input value. ●Every time the user types, 'onChange' updates the state. ●The input always displays the value from React state. ✅ Best for validation, dynamic UI updates, and complex forms. 🟠 Uncontrolled Component An uncontrolled component stores its data in the DOM, not in React state. 👉 React accesses the value only when needed using 'useRef'. Example: import { useRef } from "react"; function UncontrolledForm() { const nameRef = useRef(); const handleSubmit = () => { alert(nameRef.current.value); }; return ( <> <input type="text" ref={nameRef} /> <button onClick={handleSubmit}>Submit</button> </> ); } Here ●The input manages its own value internally. ●'useRef' is used to access the value when the button is clicked. ●React does not track every keystroke. ✅ Best for simple forms or quick implementations. 💡 Difference: ■Controlled → React controls the data. ■Uncontrolled → DOM controls the data. Understanding this concept helps in building cleaner, more predictable, and scalable React applications. #ReactJS #FrontendDevelopment #JavaScript #WebDevelopment #ReactLearning
Controlled vs Uncontrolled Components in React: State Management
More Relevant Posts
-
I was using useEffect for every API call in React. It worked. But it was a mess. 😅 This is what my code looked like: const UserList = () => { const [users, setUsers] = useState([]) const [loading, setLoading] = useState(false) const [error, setError] = useState(null) useEffect(() => { setLoading(true) fetchUsers() .then(data => setUsers(data)) .catch(err => setError(err)) .finally(() => setLoading(false)) }, []) if (loading) return <div>Loading...</div> if (error) return <div>Error!</div> return users.map(user => <UserCard user={user} />) } 3 useState calls. Manual loading/error handling. No caching. No refetching. Code repeated in every component. 😔 Then I discovered React Query: const UserList = () => { const { data, isLoading, error } = useQuery({ queryKey: ['users'], queryFn: fetchUsers }) if (isLoading) return <div>Loading...</div> if (error) return <div>Error!</div> return data.map(user => <UserCard user={user} />) } Same result. But: ✅ No manual loading state ✅ No manual error handling ✅ Automatic caching ✅ Background refetching ✅ 70% less code Rule I follow now: → Server state = React Query → UI state = useState → Complex state = useReducer Wish I knew this earlier. 🚀 Are you still using useEffect for API calls? Comment below! 👇 #ReactJS #JavaScript #Frontend #WebDevelopment #ReactQuery #CleanCode
To view or add a comment, sign in
-
-
Day 12: useEffect Hook in React If useState handles data, then useEffect handles side effects. Understanding this hook is key to building real-world React applications. 📌 What is useEffect? useEffect is a React Hook used to perform side effects in functional components. Side effects include: • API calls • Fetching data • Updating the DOM • Setting up subscriptions • Timers (setInterval, setTimeout) 📌 Basic Syntax useEffect(() => { // side effect code }, [dependencies]); 📌 Example: Run on Component Mount import { useEffect } from "react"; function App() { useEffect(() => { console.log("Component Mounted"); }, []); return <h1>Hello React</h1>; } 👉 Empty dependency array [] means it runs only once (like componentDidMount). 📌 Example: Run on State Change import { useState, useEffect } from "react"; function Counter() { const [count, setCount] = useState(0); useEffect(() => { console.log("Count changed:", count); }, [count]); return ( <button onClick={() => setCount(count + 1)}> {count} </button> ); } 👉 Runs every time count changes. 📌 Cleanup Function (Very Important) useEffect(() => { const interval = setInterval(() => { console.log("Running..."); }, 1000); return () => clearInterval(interval); }, []); 👉 Prevents memory leaks by cleaning up effects. 📌 Why useEffect is powerful ✅ Handles API calls ✅ Syncs UI with data ✅ Manages lifecycle in functional components ✅ Keeps code clean and organized #ReactJS #useEffect #FrontendDevelopment #JavaScript #WebDevelopment #CodingJourney
To view or add a comment, sign in
-
Using useEffect for every API call in React. It worked. But it was a mess. 😅 This is what my code looked like: const UserList = () => { const [users, setUsers] = useState([]) const [loading, setLoading] = useState(false) const [error, setError] = useState(null) useEffect(() => { setLoading(true) fetchUsers() .then(data => setUsers(data)) .catch(err => setError(err)) .finally(() => setLoading(false)) }, []) if (loading) return <div>Loading...</div> if (error) return <div>Error!</div> return users.map(user => <UserCard user={user} />) } 3 useState calls. Manual loading/error handling. No caching. No refetching. Code repeated in every component. 😔 Then I discovered React Query: const UserList = () => { const { data, isLoading, error } = useQuery({ queryKey: ['users'], queryFn: fetchUsers }) if (isLoading) return <div>Loading...</div> if (error) return <div>Error!</div> return data.map(user => <UserCard user={user} />) } Same result. But: ✅ No manual loading state ✅ No manual error handling ✅ Automatic caching ✅ Background refetching ✅ 70% less code Rule I follow now: → Server state = React Query → UI state = useState → Complex state = useReducer Wish I knew this earlier. 🚀 Are you still using useEffect for API calls? Comment below! 👇 #ReactJS #JavaScript #Frontend #WebDevelopment #ReactQuery #CleanCode
To view or add a comment, sign in
-
-
𝐃𝐢𝐝 𝐲𝐨𝐮 𝐤𝐧𝐨𝐰 𝐑𝐞𝐚𝐜𝐭.𝐦𝐞𝐦𝐨 𝐦𝐢𝐠𝐡𝐭 𝐛𝐞 𝐥𝐲𝐢𝐧𝐠 𝐭𝐨 𝐲𝐨𝐮 𝐚𝐛𝐨𝐮𝐭 𝐩𝐫𝐞𝐯𝐞𝐧𝐭𝐢𝐧𝐠 𝐫𝐞-𝐫𝐞𝐧𝐝𝐞𝐫𝐬? It's a fantastic tool for performance, but many developers hit a wall when their memoized component still re-renders unexpectedly. The culprit? Reference equality. `React.memo` does a shallow comparison of props. This works perfectly for primitives (strings, numbers, booleans). But when you pass objects, arrays, or functions directly as props, `React.memo` will see a "new" reference on every parent re-render, even if the contents haven't changed. Example: ```javascript const MyComponent = React.memo(({ data, onClick }) => { /* ... */ }); // In parent component: <MyComponent data={{ id: 1 }} onClick={() => console.log('clicked')} /> // ^ data and onClick will be new references on every parent render ``` Even if `id: 1` is always the same, `{ id: 1 }` creates a new object in memory each time, failing the `React.memo` check. Same goes for inline functions. The fix? Leverage `useMemo` for objects/arrays and `useCallback` for functions to ensure stable references across renders. ```javascript const memoizedData = useMemo(() => ({ id: 1 }), []); const memoizedOnClick = useCallback(() => console.log('clicked'), []); <MyComponent data={memoizedData} onClick={memoizedOnClick} /> ``` This ensures your props maintain the same reference, allowing `React.memo` to do its job effectively. It's a small detail, but crucial for optimizing complex React apps. Have you encountered this `React.memo` gotcha before? How did you debug it? #React #Frontend #Performance #JavaScript #WebDevelopment
To view or add a comment, sign in
-
🚨 Debouncing won’t fix this React bug You already fixed: ❌ Too many API calls (debounce) But there’s another hidden problem. Even with debounce… Your UI can still show wrong data. Example: useEffect(() => { fetch(`/api/search?q=${query}`) .then(res => res.json()) .then(data => setResults(data)) }, [query]) User types: a → ap → app → apple Now imagine: Request 1 → slow Request 2 → fast Result: ❌ Old data overrides new data ❌ UI shows incorrect results This is a race condition. --- 💡 Fix: cancel previous requests useEffect(() => { const controller = new AbortController() fetch(`/api/search?q=${query}`, { signal: controller.signal }) .then(res => res.json()) .then(data => setResults(data)) return () => controller.abort() }, [query]) Now only the latest request updates the UI. --- 💡 Good React engineers don’t just reduce API calls. They ensure correct data is shown. #reactjs #frontend #javascript #webdevelopment
To view or add a comment, sign in
-
-
🚨 Why your React component re-renders (even when nothing changes) A lot of times we feel like: “Nothing changed… but my component re-rendered.” Actually, React always has a reason. Here are the real triggers 👇 🔁 What causes re-renders? • State change (useState) • Parent component re-render • Context value change • Props reference change ⚠️ The most ignored one: Reference change React does NOT check deep values. It only checks references. So even if data looks same, React treats it as new. Example: const obj = { name: "Dhana" }; This creates a new object every time → new reference → re-render ❌ Common mistake <MyComponent data={{ name: "Dhana" }} /> Looks fine, but this creates a new object on every render. ✅ Better way const data = useMemo(() => ({ name: "Dhana" }), []); <MyComponent data={data} /> Now reference stays same → no unnecessary re-render Don’t overuse useMemo/useCallback. Use them only when: 👉 re-renders are actually causing performance issues Understanding this one concept can level up your React skills a lot. #ReactJS #Frontend #WebDevelopment #JavaScript #Performance
To view or add a comment, sign in
-
⚛️ React Performance Tip: Stop Recomputing on Every Render A common mistake in React is recalculating data on every render: ```javascript id="s7dh2k" const processedData = data.map(...); ``` ❌ This runs every time the component re-renders ❌ Leads to unnecessary computation and slower UI Instead, memoize it using `useMemo`: ```javascript id="k39xdl" const processedData = useMemo(() => { return data.map(...); }, [data]); ``` ✅ Runs only when `data` changes ✅ Prevents unnecessary recalculations ✅ Improves performance significantly 💡 Key takeaway: Use `useMemo` when: • Expensive computations • Large datasets • Avoiding repeated work 🚀 Small optimization = big performance boost What’s your go-to React performance trick? #ReactJS #JavaScript #Frontend #Performance #WebDevelopment #Coding
To view or add a comment, sign in
-
-
⚡ 5 Custom React Hooks That Saved Me Hours Stop repeating logic! Build reusable hooks: 1️⃣ useFetch (API Calls) function useFetch(url) { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { fetch(url) .then(res => res.json()) .then(setData) .catch(setError) .finally(() => setLoading(false)); }, [url]); return { data, loading, error }; } 2️⃣ useLocalStorage (Persistent State) function useLocalStorage(key, initialValue) { const [value, setValue] = useState(() => { const saved = localStorage.getItem(key); return saved ? JSON.parse(saved) : initialValue; }); useEffect(() => { localStorage.setItem(key, JSON.stringify(value)); }, [key, value]); return [value, setValue]; } 3️⃣ useDebounce (Search Optimization) 4️⃣ useWindowSize (Responsive Logic) 5️⃣ useToggle (Boolean State) Benefits: ✅ DRY (Don't Repeat Yourself) ✅ Easier testing ✅ Cleaner components ✅ Reusable across projects Custom hooks = Superpower! 💪 What custom hooks do you use? 👇 #React #CustomHooks #WebDevelopment #JavaScript #CleanCode
To view or add a comment, sign in
-
Day 11: useState Hook in Depth If you understand useState, you understand how React handles dynamic data. It’s one of the most important hooks in React. 📌 What is useState? useState is a React Hook that allows functional components to manage state (data that changes over time). 📌 Basic Syntax const [state, setState] = useState(initialValue); • state → current value • setState → function to update value • initialValue → starting value 📌 Example: Counter import { useState } from "react"; function Counter() { const [count, setCount] = useState(0); return ( <div> <h1>{count}</h1> <button onClick={() => setCount(count + 1)}> Increase </button> </div> ); } Each click updates the state and React re-renders the UI automatically. 📌 Updating State Correctly State updates are asynchronous, so always use the previous state when needed: setCount(prevCount => prevCount + 1); 📌 useState with Objects const [user, setUser] = useState({ name: "", age: 0 }); setUser({ ...user, name: "John" }); Always use spread operator to avoid losing other values. 📌 Multiple States const [name, setName] = useState(""); const [age, setAge] = useState(0); You can create multiple state variables in one component. 📌 Why useState is powerful ✅ Makes UI dynamic ✅ Triggers re-render automatically ✅ Simple and easy to use ✅ Core of modern React apps #ReactJS #useState #FrontendDevelopment #JavaScript #WebDevelopment #CodingJourney
To view or add a comment, sign in
-
🚀 useState in React 🧠 useState is one of the most important hooks in React. It lets your component remember and update data. 1️⃣ Basic Example import { useState } from "react"; function Counter() { const [count, setCount] = useState(0); return ( <button onClick={() => setCount(count + 1)}> {count} </button> ); } 2️⃣ What’s happening here? const [count, setCount] = useState(0); ✔ count → current state value ✔ setCount → function to update state ✔ 0 → initial value 3️⃣ Important Rule ⚠️ 👉 Never update state like this: count = count + 1 ❌ 👉 Always use setter: setCount(count + 1) ✅ 4️⃣ Why useState triggers re-render? When you call: setCount(5); 👉 React: Stores new value Re-renders component Updates UI 5️⃣ Real World Example function InputBox() { const [name, setName] = useState(""); return ( <input value={name} onChange={(e) => setName(e.target.value)} /> ); } 👉 This is called a controlled component 6️⃣ Updating Based on Previous State setCount(prev => prev + 1); 👉 Best practice when new value depends on old value 7️⃣ Multiple States const [name, setName] = useState(""); const [age, setAge] = useState(20); 👉 Each state is independent 🔥 Key Takeaway useState = Store + Update + Re-render UI #React #JavaScript #Frontend #WebDevelopment #LearningByDoing
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