
setState 함수로 변경state를 관리하는 훅, 다양한 데이터 타입을 상태로 관리 가능.
useState
const [변수명, set함수명] = useState(초기값);import React, { useState } from 'react';
const Counter = () => {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};
export default Counter;
라이프사이클을 관리하는 훅, 컴포넌트의 렌더링이 끝난 후 실행되어야 하는 기능에 사용
useEffect(이펙트 함수, 의존성 배열);
[] => mount시 단 한 번만import React, { useState, useEffect } from 'react';
const ExampleA = () => {
const [count, setCount] = useState(0);
useEffect(() => {
console.log('Effect ran');
});
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};
export default ExampleA;
import React, { useState, useEffect } from 'react';
const ExampleA = () => {
const [count, setCount] = useState(0);
useEffect(() => {
console.log('Effect ran');
});
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};
export default ExampleA;
import React, { useState, useEffect } from 'react';
const MyComponent = () => {
const [count, setCount] = useState(0);
useEffect(() => {
const subscription = someService.subscribe();
console.log('Effect ran');
// Returning a cleanup function
return () => {
someService.unsubscribe(subscription);
console.log('Cleanup function executed');
};
}, [count]);
return (
<div>
<button onClick={() => setCount(count + 1)}>
Increase Count
</button>
</div>
);
};