nova / react.txt
crazysanthosh's picture
Upload 25 files
7fde9b9 verified
Raw History Blame Contribute Delete
7.43 kB
## React Hooks - useState
Definition: useState is a React Hook that lets you add state to functional components. It returns the current state value and a function to update it.
Explanation: Before hooks, only class components could have state. useState accepts an initial value (or a function for expensive initialization). The state update function can take a new value or an updater function. State updates are asynchronous and batch together in event handlers.
Example: A simple counter with increment and decrement buttons.
Code Example:
```jsx
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
// Functional update - always safe for derived values
const increment = () => setCount(prev => prev + 1);
const decrement = () => setCount(prev => prev - 1);
const reset = () => setCount(0);
return (
<div>
<h2>Count: {count}</h2>
<button onClick={increment}>+</button>
<button onClick={decrement}>-</button>
<button onClick={reset}>Reset</button>
</div>
);
}
```
Best Practices: Use the functional update form (prev => ...) when new state depends on old state. Group related state into an object or use useReducer for complex state. Don't mutate state directly — always use the setter.
Common Errors: Setting state is asynchronous — don't read it immediately after. Infinite re-renders from calling setState in the body of the component without conditions. Storing derived data in state instead of computing it on render.
Interview Questions: What is the difference between useState and useReducer? When does React batch state updates? What causes infinite re-render loops?
## React Hooks - useEffect
Definition: useEffect is a React Hook that lets you synchronize a component with external systems (API calls, subscriptions, timers, DOM manipulation).
Explanation: useEffect runs after every render by default. The dependency array controls when it re-runs: [] runs once on mount, [dep1, dep2] runs when deps change, omitting it runs on every render. The cleanup function (returned function) runs before the next effect and on unmount — essential for preventing memory leaks.
Example: Fetching data when a userId prop changes, with cleanup.
Code Example:
```jsx
import { useState, useEffect } from 'react';
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
let cancelled = false; // Prevent stale state update
async function fetchUser() {
setLoading(true);
const res = await fetch(`/api/users/${userId}`);
const data = await res.json();
if (!cancelled) {
setUser(data);
setLoading(false);
}
}
fetchUser();
return () => { cancelled = true; }; // Cleanup
}, [userId]); // Re-run when userId changes
if (loading) return <p>Loading...</p>;
return <h2>{user?.name}</h2>;
}
```
Best Practices: Always clean up subscriptions, timers, and event listeners. Include all reactive values in the dependency array (use ESLint react-hooks/exhaustive-deps). Use AbortController for cancellable fetch requests.
Common Errors: Missing dependencies causes stale closures. Not cleaning up leads to memory leaks and setting state on unmounted components. Putting objects/arrays in deps without memoization causes infinite loops.
Interview Questions: How do you prevent an API call from setting state on an unmounted component? When does the cleanup function run? What does an empty dependency array [] mean?
## React Context API
Definition: React Context provides a way to pass data through the component tree without manually passing props at every level (prop drilling).
Explanation: Create context with React.createContext(defaultValue). A Provider component makes the value available to all descendants. useContext(MyContext) consumes the value in any child. Context is best for global data: theme, language, auth status. Overuse causes unnecessary re-renders — every context consumer re-renders on context change.
Example: A theme context that provides dark/light mode to the entire app.
Code Example:
```jsx
import { createContext, useContext, useState } from 'react';
const ThemeContext = createContext('light');
function ThemeProvider({ children }) {
const [theme, setTheme] = useState('light');
const toggle = () => setTheme(t => t === 'light' ? 'dark' : 'light');
return (
<ThemeContext.Provider value={{ theme, toggle }}>
{children}
</ThemeContext.Provider>
);
}
function ThemedButton() {
const { theme, toggle } = useContext(ThemeContext);
return (
<button
style={{ background: theme === 'dark' ? '#333' : '#fff' }}
onClick={toggle}
>
Toggle Theme ({theme})
</button>
);
}
```
Best Practices: Split contexts by concern (AuthContext, ThemeContext separately). For complex global state, prefer Zustand or Redux. Memoize context values to prevent unnecessary re-renders.
Common Errors: Passing a new object as context value on every render causes all consumers to re-render. Forgetting to wrap the app with the Provider. Using context for frequently-changing values (use Zustand instead).
Interview Questions: What is prop drilling and how does Context solve it? What are the performance implications of Context? When would you use Context vs Zustand/Redux?
## React Performance Optimization
Definition: React renders components efficiently but may re-render unnecessarily. Optimization techniques prevent wasted renders and improve responsiveness.
Explanation: React.memo() prevents re-rendering if props didn't change. useMemo() memoizes computed values. useCallback() memoizes functions (stable reference across renders). Key prop on list items tells React how to reconcile. React DevTools Profiler identifies bottlenecks. Virtualization (react-window) for large lists.
Example: Memoizing an expensive computation and preventing child re-renders.
Code Example:
```jsx
import { useState, useMemo, useCallback, memo } from 'react';
// Memoized child - won't re-render unless onSubmit changes
const ExpensiveButton = memo(({ onSubmit }) => {
console.log('Button rendered');
return <button onClick={onSubmit}>Submit</button>;
});
function Parent() {
const [count, setCount] = useState(0);
const [items, setItems] = useState([1,2,3,4,5]);
// useMemo - only recomputes when items changes
const total = useMemo(() => {
return items.reduce((sum, n) => sum + n, 0);
}, [items]);
// useCallback - stable function reference
const handleSubmit = useCallback(() => {
console.log('Submitted! Total:', total);
}, [total]);
return (
<div>
<p>Count: {count}</p>
<p>Total: {total}</p>
<button onClick={() => setCount(c => c + 1)}>Re-render Parent</button>
<ExpensiveButton onSubmit={handleSubmit} />
</div>
);
}
```
Best Practices: Profile before optimizing — don't prematurely memoize. Keys on list items must be unique and stable. Use code splitting (React.lazy + Suspense) for large components.
Common Errors: Using array index as key breaks reconciliation on reorder. Wrapping everything in useMemo/useCallback adds overhead without benefit. Not using the Profiler — optimizing the wrong thing.
Interview Questions: What is reconciliation in React? When should you use useMemo vs useCallback? Why should you avoid using array indexes as keys?