React Hook은 React에서 class의 기능, state나 componentDidMount등을 function에서도 사용할 수 있게 해줍니다.
function Aaa(){
const [count, setCount]=useState(0);
useEffect(()=>{
console.log(count);
return ()=>{console.log("disappeared");}
}
()=>{
return(
<div onClick={()=>setCount(count+1)}>{count}</div>
);
}
const [count,setCount]=useState(0);
으로 함수에서도 state를 사용할 수 있습니다. useState의 인자 0으로 count가 초기화되고, setCount로 count를 변경할 수 있습니다.
useEffect의 인자로 들어가는 함수는 렌더링이 될 때마다, 즉 처음 mount될 때와 update될 때마다 실행됩니다. 이 함수가 return하는 함수는 clean-up될 때 실행됩니다.
useEffect에는 두 번째 인자로 배열을 줄 수 있는데, 이 경우 배열안의 state들이 바뀌었을 때만 첫번째 인자의 함수가 실행됩니다.