useEffect 조건부 랜더링
const FetchDate = () => {
const [isLoading, setIsLoading] = useState(true);
const [isError, setIsError] = useState(false);
const [user, setUser] = useState(null);
if(isLoading){
return <h2>Loding...</h2>;
}
useEffect(()=>{
const fetchUser = async() => {
try{
const resp = await fetch(url);
if(!resp.ok) {
setIsError(true);
setIsLoading(false);
return;
}
const user = await resp.json();
setUser(user);
} catch (error) {
setIsError(true);
}
setIsLoading(false);
}
fetchUser();
}, []);
if(isLoading){
return <h2>Loding...</h2>;
}
if(isError){
return <h2>There was an error...</h2>;
}
return (
<section>
<h2>{user.name}</h2>
</section>
)
}
mounted, unmounted 일때 함수 실행
기본 예제
const ToggleButton = () => {
const [toggle, setToggle] = useState(false);
return (
<div>
<button onClick={()=>setToggle(!toggle)}>
toggle component
</button>
{toggle && <RandomComponent />}
</div>
);
}
const RandomComponent = () => {
useEffect(()=>{
const intId = setInterval(()=>{
console.log('hello from interval');
}, 1000);
return () => {
clearInterval(intId);
}
}, []);
return <h1>Random Component</h1>;
}
export default ToggleButton;
window eventListner
const RandomComponent = () => {
useEffect((()=>{
const someFunc = () => {
...
}
window.addEventListner('scroll', someFunc);
window.removeEventListner('scroll', someFunc);
}), []);
return <h1>hello</h1>;
}
Docs 읽어보기
https://react.dev/learn/you-might-not-need-an-effect