Silver Library (Archived)
So, how to useEffect? 본문
What is this?
useEffect is a hook in React that allows us to synchronise a component with an external system.
This can be used to handle a variety of tasks, like:
1. setting up a subscription
2. manually changing the DOM
3. fetching data
First of all, this is the typical and basic useEffect.
import { useEffect } from 'react';
function MyComponent() {
useEffect(() => {
// your code here
}, [dependencies]);
// rest of your component's code here
}
The first argument to useEffect is a function that contains the code we want to run.
This function is called an effect function. Inside this function, we can do things liek set up a subscription, fetch data, or change the DOM.
The second argument to useEffect is an array of dependencies. These are values from the component's state or props that we want to watch.
When any of these dependencieis change, React will re-run the effect function.
There was an example of using useEffect to subscribe to an external data source:
import { useEffect, useState } from 'react';
function MyComponent({ id }) {
const [data, setData] = useState(null);
useEffect(() => {
const subscription = someDataSource.subscribe(id, data => {
setData(data);
});
return () => {
subscription.unsubscribe();
};
}, [id]);
if (data === null) {
return <p>Loading...</p>;
}
return <p>Data: {data}</p>;
}
The component is subscribing to some external data source and passing an id prop to it.
Once the component is rendered, useEffect is called with an effect function that sets up the subscription and provides a cleanup function, which is called when the component is unmounted.
The component state is updated with the returned data and the component re-render the updated data.
'F5. Library of Tools > React.js' 카테고리의 다른 글
미궁의 react hook form, 대체 어떻게 전달될까. (0) | 2023.02.25 |
---|---|
Crash note - list, key, fake data generator (0) | 2023.01.28 |
OOP, but how with reactjs? (0) | 2023.01.11 |