[React] 함수형 컴포넌트의 훅(Hook)을 정리해보자
◽ useState
초기 렌더링 시에 사용하는 state로, 이후의 렌더링 시에는 이 값은 무시된다.
function Counter({initialCount}) {
const [count, setCount] = useState(initialCount);
return (
<>
Count: {count}
<button onClick={() => setCount(initialCount)}>Reset</button>
<button onClick={() => setCount(prevCount => prevCount - 1)}>-</button>
<button onClick={() => setCount(prevCount => prevCount + 1)}>+</button>
</>
);
}
📄 setter를 사용하여 값 변경하기
// 배열
const [category, setCategory] = useState([
[CategoryType.CHARACTER]: {
isOpen: false,
},
[CategoryType.CATEGORY]: {
isOpen: false,
},
])
const handleClickOpen = (type: CategoryType) => {
setCategory(
category.map((category) =>
category.type === type
? { ...category, isOpen: !category.isOpen }
: category,
),
)
}
// Object
const [category, setCategory] = useState({
[CategoryType.CHARACTER]: {
isOpen: false,
},
[CategoryType.CATEGORY]: {
isOpen: false,
},
})
const handleClickOpen = (type: CategoryType) => {
setCategory({
...category,
[CategoryType[type]]: {
isOpen: !category[type].isOpen,
},
})
}
컴포넌트가 재렌더링이 되면 다른 원시값이 할당된다.
◽ useEffect
componentDidMount와 componentDidUpdate와는 달리 useEffect로 전달된 함수는 지연 이벤트 동안에 레이아웃 배치와 그리기를 완료한 후에 발생한다.
useEffect는 여러개 사용할 수 있다.
유형 1. 렌더링 될 때 마다 계속 실행
인자를 받지 않고 콜백만 선언한다.
useEffect(() => {
// code...
})
유형 2. Mount 이후로 1회만 실행
빈 배열로 선언한다.
useEffect(() => {
// code...
}, [])
유형 3. 어떤 요소가 바뀔 때 실행
두번째 인자에 지켜볼 인자를 넣어준다. 전달되는 props가 변경되거나, 내부 state가 변경되는 경우에 실행된다.
useEffect(() => {
// code...
}, [props명, state명, ...])
유형 4. 함수 Clean Up
useEffect(() => {
const subscription = props.source.subscribe();
return () => {
// Clean up the subscription
subscription.unsubscribe();
};
});
useEffect(() => {
return () => {
// 여기에 unmount나 unsubscribe 코드 작성
}
}, [])
useEffect(() => {
return () => {
// 여기에 unmount나 unsubscribe 코드 작성
}
}, [props명, state명, ...])
만약 useEffect를 쓰면서 문제가 발생한다면 useLayoutEffect를 사용한다. useLayoutEffect은 DOM에서 레이아웃을 읽고 동기적으로 리렌더링하는 경우에 사용하면 된다. ($nextTick 같은 걸까..?)
◽ useContext
이중 삼중 깊이로 props를 넘길 때 사용한다.
예시) 로그인 시 유저의 정보를 저장
<ThemeContext.Provider value={themes.dark}>
<Toolbar />
</ThemeContext.Provider>
useContext 안에 전달하는 인자는 '객체'임을 잊지 말아야 한다.
const value = useContext(MyContext); // O
const value = useContext(MyContext.Provider); // X
◽ useRef
useRef는 순수 자바스크립트 객체를 생성한다. 단, 내용이 변경될 때 알려주지는 않는다.
📄 예제 1.
function TextInputWithFocusButton() {
const inputEl = useRef(null);
const onButtonClick = () => {
// `current` points to the mounted text input element
inputEl.current.focus();
};
return (
<>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</>
);
}
📄 예제 2.
function CustomTextInput(props) {
// textInput은 ref 어트리뷰트를 통해 전달되기 위해서 이곳에서 정의되어야 한다.
const textInput = useRef(null);
function handleClick() {
textInput.current.focus();
}
return (
<div>
<input
type="text" ref={textInput} />
<input
type="button"
value="Focus the text input"
onClick={handleClick}
/>
</div>
);
}
createRef()는 클래스형 컴포넌트에서 사용한다.
출처
Hooks API Reference – React
A JavaScript library for building user interfaces
ko.reactjs.org
Why React Hook useState uses const and not let
The standard way to use a React useState Hook is the following: const [count, setCount] = useState(0); However this const count variable is clearly going to be reassigned to a different primitive...
stackoverflow.com
개인적으로 공부한 내용을 정리하는 블로그로
잘못된 개념을 게시하지않도록 주의하고 있으나 오류가 있을 수 있습니다.