- Регистрация
- 1 Мар 2015
- Сообщения
- 1,481
- Баллы
- 155
Destructuring & PropsA short but powerful summary to remind you of core React patterns like useEffect, useContext, useRef, and custom hooks — ideal for job interview prep or daily development.
Basic prop extraction with default values or rest:
const { title, handleClick, ...rest } = props;
Used frequently to simplify prop passing, like:
<Card title={title} onClick={handleClick} {...rest} />
useEffect
useEffect runs side effects (data fetching, event listeners, DOM updates). Syntax:
useEffect(() => {
// effect code
return () => {
// cleanup
};
}, [dependencies]);
Don’t do this:
useEffect(() => {
fetchData(); // this shouldn't be called directly without dependency control
});
Execution Timeline
First Render:
→ useEffect runs
→ cleanup not called
Second Render:
→ cleanup called
→ useEffect runs again
Third Render:
→ cleanup called
→ useEffect runs again
Context API
An alternative to props for global/shared state.
1. Create Context
import { createContext } from 'react';
export const BookContext = createContext();
2. Provide Context
<BookContext.Provider value={value}>
<MyComponent />
</BookContext.Provider>
3. Consume Context
import { useContext } from 'react';
const value = useContext(BookContext);
Perfect for global state like user info, theme, or counters.
useCallback
Avoid unnecessary re-renders by memoizing function references:
const stableFunction = useCallback(() => {
fetchBooks();
}, []);
Behaves similarly to useEffect with its dependency array.
Custom Hooks
Encapsulate logic:
function useCounter() {
const [count, setCount] = useState(0);
const increment = () => setCount(count + 1);
return { count, increment };
}
Usage:
const { count, increment } = useCounter();
useRef
Used to persist mutable values or access DOM nodes:
const inputRef = useRef();
useEffect(() => {
inputRef.current.focus();
}, []);
- Create a ref → useRef()
- Attach to DOM → <input ref={inputRef} />
- Access → inputRef.current
| Application State | Component State |
|---|---|
| Shared across many components | Used in a single component |
| Good for Context | Good for local state |
Event Propagation: Capture vs BubbleIt's usually a good idea to elevate application state into context for global use.
React handles events in the bubbling phase by default. Use capture if needed:
document.addEventListener('click', handler, true); // capture = true
Cleanup Flow in useEffect
useEffect(() => {
const handler = () => console.log('clicked');
document.addEventListener('click', handler);
return () => {
document.removeEventListener('click', handler);
};
}, []);
Always clean up listeners, intervals, or subscriptions.
Summary
- useEffect → Side effects with cleanup
- useContext → Global/shared state
- useCallback → Stable function refs
- useRef → DOM access and value persistence
- Custom Hooks → Reusable logic extraction
- Context API → Replaces prop drilling