The goal from this discussion is to solidify your understanding about useEffect after studying about it before the class and in the class.
Please discuss the following questions between you and answer them in the comment section below.
Questions:
- What is
useEffect
? - What do we mean when we say that useEffect is a hook?
- useEffect gets executed in 3 different ways, what are they? (Adding code examples would be beneficial)
Selepe Thinane
Mthokozisi Dlamini
lethukuthula Mkhondo
useEffect is react hook that can be used perform side effects
is a hook because it's a special function you can "hook" into your React components
useEffect can be executed on every render / at the beginning and when changes occur
const MyComponent = () => {
const [data, setData] = useState(null); // Assume
useState
for datauseEffect(() => {
console.log('This runs after every render');
});
useEffect(() => {
// Fetch data on initial render (empty dependency array)
fetchData().then(data => setData(data));
}, []);
useEffect(() => {
// Do something whenever data changes (dependency on
data
)if (data) {
console.log("Data received:", data);
}
}, [data]);
return (
{data &&
Fetched data: {data}
});
};