setState를 사용할 때마다 실행된다.
하지만, component가 처음 render될 때만 실행되길 원할 때도 있다.
useEffect를 사용한다.
2개의 argument가 있다. useEffect(function, [])
useEffect function은 코드가 딱 한번만 실행될 수 있도록 보호해준다.
function App() {
const [counter, setValue] = useState(0);
const onClick = () => setValue((prev) => prev + 1);
console.log("i run all the time");
// 1번만 실행된다.
useEffect(() => {
console.log("i run only once.");
}, []);
keyword가 변경될 때만 실행시키고 싶다면, useEffect(function, [keyword])
로 작성하면 된다.
useEffect(() => {
console.log("I run when 'keyword' changes.");
}, [keyword]);
useEffect(() => {
console.log("I run when keyword or counter change");
}, [keyword, counter]);
react는 새로운 데이터가 들어올때마다 component를 refresh해준다.
변화가 일어날 때마다 refresh해준다.
하지만, 한번만 실행하고 싶은 코드가 있을 수 있다. 이 때 사용하는 것이 useEffect이다!
useEffect는 2개의 argument를 가지는 function이다.
실행할 함수, dependencies를 argument로 가진다.
cleanup function
: component가 destroy될 때 무엇인가 할 수 있도록 해준다!
function Hello() {
function byeFn() {
console.log("bye bye");
}
function hiFn() {
console.log("hi hi");
return byeFn; // cleanup Function
}
useEffect(hiFn, []);
return <h1>Hello</h1>;
보통 cleanup function은 아래와 같이 사용한다.
import { useState, useEffect } from "react";
function Hello() {
useEffect(() => {
console.log("hi :)");
// cleanup function
return () => console.log("bye :(");
}, []);
return <h1>Hello</h1>;
}
function App() {
const [showing, setShowing] = useState(false);
const onClick = () => setShowing((prev) => !prev);
return (
<div>
{showing ? <Hello /> : null}
<button onClick={onClick}>{showing ? "Hide" : "Show"}</button>
</div>
);
}