Temel Farklılıklar:
this bağlamı (Arrow functions lexical scope'u kullanır)// React'ta kullanım örnekleri
// Class component'lerde metodlar için:
class MyComponent extends React.Component {
handleClick = () => {
// Arrow function kullanımı 'this'i korur
}
}
// Functional component'lerde:
function MyComponent() {
// Event handler'lar için:
const handleClick = useCallback(() => {
// Memorize edilmiş callback
}, []);
}
Kompleks iş mantığını küçük, yeniden kullanılabilir fonksiyonlara bölme:
const withAuth = (Component) => (props) => {
const { user } = useAuth();
return user ? : ;
};
const withLogging = (Component) => (props) => {
useEffect(() => {
logAnalytics(props);
}, []);
return ;
};
// Kullanım:
const EnhancedComponent = withLogging(withAuth(MyComponent));
// useCallback: Fonksiyon referanslarını sabitlemek için
const memoizedCallback = useCallback(
() => doSomething(a, b),
[a, b]
);
// useMemo: Hesaplamalı değerleri cache'lemek için
const memoizedValue = useMemo(
() => computeExpensiveValue(a, b),
[a, b]
);
Optimizasyon Stratejisi: Sadece child component'lere prop geçerken veya hesaplama maliyeti yüksekse kullanın
function useDebounce(value, delay) {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => clearTimeout(handler);
}, [value, delay]);
return debouncedValue;
}
// Kullanım:
const debouncedSearchTerm = useDebounce(searchTerm, 500);
State'i mümkün olduğunca küçük parçalara bölme:
// Kötü:
const [user, setUser] = useState({ name: '', email: '', preferences: {} });
// İyi:
const [name, setName] = useState('');
const [email, setEmail] = useState('');
// Her state parçası izole şekilde güncellenebilir
const [state, send] = useMachine({
initial: 'idle',
states: {
idle: { on: { FETCH: 'loading' } },
loading: { on: { RESOLVE: 'success', REJECT: 'error' } },
success: {},
error: {}
}
});
XState veya benzeri kütüphanelerle kompleks state mantığını yönetme
// React-window ile liste optimizasyonu
import { FixedSizeList as List } from 'react-window';
const Row = ({ index, style }) => (
<div style={style}>Row {index}</div>
);
const Example = () => (
<List height={600} itemCount={1000} itemSize={35} width={300}>
{Row}
</List>
);
// Main thread'den ağır hesaplamaları çıkarma
const worker = new Worker('worker.js');
function HeavyComponent() {
const [result, setResult] = useState(null);
useEffect(() => {
worker.onmessage = (e) => setResult(e.data);
worker.postMessage({ data: largeDataSet });
}, []);
}