React
[React] Hook : useState, useEffect, useRef, useContext
떼굴펜
2024. 5. 20. 20:43
useState
: 컴포넌트에 state 변수를 추가할 수 있다 (공식 문서)
const [state, setState] = useState(initialState);
- initialState : 초기 설정값
const [age, setAge] = useState(28);
console.log(age); // 28
setAge(30);
console.log(age); // 30
useEffect
: 외부 환경과 같은 생명주기를 가질 수 있다 (공식 문서)
useEffect( setup, dependencies? );
- setup : Effect의 로직이 포함된 기능입니다. 선택적으로 정리 함수를 반환할 수도 있습니다.
- dependencies : 값이 변경될 때마다 setup을 실행합니다. 변경되는 걸 감지할 값들을 배열로 전달합니다.
useEffect(()=>{
console.log("mount 될 때 동작합니다.");
return () => { // 정리 함수 반환
console.log("unmount 될 때 동작합니다.");
}
}, []);
useRef
: 렌더링에 필요하지 않은 값을 참조할 수 있다. (공식 문서)
const ref = useRef( initialValue );
- initialState : 초기 설정값
const ref = useRef("최초");
console.log(ref); // { current : "최초" }
ref.current = "변경";
console.log(ref); // { current : "변경" }
useContext
: 컴포넌트에서 context를 읽고 구독할 수 있다. (공식 문서)
❗context value 가 변경되면 context를 사용하고 있던 모든 컴포넌트가 리렌더링되기에 주의해서 사용해야 한다.
// FamilyContext.js
import {createContext} from "react";
export const FamilyContext = createContext(null);
// GrandFather.jsx
export default GrandFather () {
const name = "떼굴펜";
const age = 20;
return (
<FamilyContext.Provider value = {{ name, age }} >
<Father />
</FamilyContext.Provider>
);
}
// Child.jsx
....
const { name, age } = useContext(FamilyContext);
console.log(name, age); // 떼굴펜, 20
....