출처 : 패스트캠퍼스 한 번에 끝내는 프론트엔드 개발 초격차 패키지
클래스에서만 가능했던 state를 함수안에서 사용 가능
종류
import React from "react";
//useState => {count : 0};
export default function Example2() {
const [state, setState] = React.useState({ count: 0 });
return (
<div>
<p>You clicked {state.count} times</p>
<button onClick={click}>Click me</button>
</div>
);
function click() {
setState((state) => ({
count: state.count + 1,
}));
}
}
import React from "react";
export default function Example5() {
const [count, setCount] = React.useState(0);
React.useEffect(() => {
console.log("componentDidMount");
return () => {};
//cleanup(다음 실행 직전에 return후 console창 출력)
//빈배열로 작성시 : 항상 render가 된 직후에 실행해라
}, []);
React.useEffect(() => {
console.log("componentDidMount & componentDidUpdate by count", count);
return () => {
//cleanup(count값 변경 되기 전의 값이 출력됨)
console.log("cleanup by count", count);
};
}, [count]);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={click}>Click me</button>
</div>
);
function click() {
setCount(count + 1);
}
}
import { useState, useEffect } from "react";
export default function useWindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
const resize = () => {
setWidth(window.innerWidth);
};
window.addEventListener("resize", () => resize);
return () => {
window.removeEventListener("resize", resize);
};
}, []);
return width;
}