Bunlar, fonksiyon tabanlı bileşenlere tepki işlevselliği eklemenize izin veren React'teki fonksiyonlardır.
Bu hook, bir bileşenin yaşam döngüsünü yönetmek için kullanılır. Sınıf tabanlı React bileşenlerinde kullanılan componentDidMount, componentDidUpdate ve componentWillUnmount yöntemlerinin amacına hizmet eder. Birkaç kullanım, bileşen takıldığında bir api getiriyor veya bileşen güncellendiğinde bileşen durumunu değiştiriyor. Sözdizimi ortak bir kalıbı takip eder:
useEffect(() => {
console.log('Component hazır olduğunda 1 kere çalışır.');
},[]);
UseEffect [] hook yalnızca bileşen monte edildiğinde çalışması için boş bırakılır. useEffect hook, bu diziye eklenen değerlerde yapılan değişiklikleri izleyecektir. Bu değerler değiştiğinde, useEffect hook çalışır. İşte bir örnek:
const [stateValue, setStateValue] = useState('');
useEffect(() => {
console.log('stateValue durumu değiştiğinde çalışır.');
},[stateValue]);
Component hazır olduğunda verileri getiren pratik bir örnek:
import { useState, useEffect } from "react";
const App = () => {
const [data, setData] = useState([]);
useEffect(() => {
const fetchData = async () => {
//Fetches a list of ten users
const response = await fetch(
"https://jsonplaceholder.typicode.com/users"
);
// If the HTTP status code is 200-299
if (response.ok) {
const json = await response.json();
setData(json);
}
};
fetchData();
}, []);
return (
<div>
<ul>
{data &&
data.map((user) => {
return <li key={user.id}>{user.name}</li>;
})}
</ul>
</div>
);
};
export default App;
useEffect hakkında daha fazla bilgiyi React belgelerinde bulabilirsin. Daha detaylı incelemek için bağlantıya tıklayın.