React & TypeScript/React
React useEffect (included api 호출) 가 있는 컴포넌트 분리 방법
yoonjong Park
2022. 4. 29. 23:08
자식 컴포넌트에서는 아래와 같이 쓰고
export const childComp = () => {
const [data, setData] = useState();
useEffect(() => {
refresh();
},[])
const refresh = () => {
fetch("URL")
.then((res)=> res.json())
.then(_newData => setData(_newData));
}
return [data, refresh];
}
부모 컴포넌트에서는 아래와 같이 쓴다.
import childComp from "./childComp";
const parentComp = () => {
const [data, refresh] = childComp();
return (
<div>
<img src={data?.message}/>
<button onClick={refresh}>
Refresh!
</button>
</div>
)
}
이게 컴포넌트를 분리하는 가장 좋은 방법이다.