1. Hook
리액트 컴포넌트는 클래스형 컴포넌트와 함수형 컴포넌트로 나뉜다. 이때, 클래스 컴포넌트는 상태관리나 Life Cycle의 기능이 있지만, 함수 컴포넌트에는 존재하지 않는다. Hook이 생기면서 함수 컴포넌트에서도 가능해지게 되었다.
const Example = (props) => {
// 여기서 Hook을 사용할 수 있다!
return <div />;
}
function Example(props) {
// 여기서 Hook을 사용할 수 있다!
return <div />;
}
2. useState
가장 기본적인 Hook으로 클래스 컴포넌트에서 this.state의 기능과 같다.
=> useState() Hook의 인자로 넘겨주는 값은 state의 초기값이다.
=> 차례로 state 변수, 해당 변수를 갱신할 수 있는 함수를 반환한다.
const [state, setState] = useState(initialState);
// state 변수 = state
// 위 변수를 갱신할 수 있는 함수 = setState
// state의 초기값 = initialState
=> 버튼을 클릭하면 값이 증가하는 카운터 예시
import React, { useState } from 'react';
// useState Hook을 React에서 가져온다.
function Example() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
// 사용자가 버튼을 클릭하면 setCount 함수를 호출하여 state 변수를 갱신한다.
// React는 새로운 count 변수를 Example 컴포넌트에 넘기며 해당 컴포넌트를 리렌더링한다.
3. useEffect
useEffect Hook은 클래스 컴포넌트에서 Life Cycle의 역할이다.
=> useEffect의 두 번째 인자에 effect가 종속되어 있는 값의 배열을 넣는데, 빈 배열을 넣으면 컴포넌트가 처음 마운트될 때에만 호출된다. 그러나, 배열에 특정 값을 넣으면 이 값이 바뀔 때마다 호출된다.
useEffect(didUpdate);
=> 버튼을 클릭하면 값이 증가하는 카운터 예시
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
// componentDidMount, componentDidUpdate와 같은 방식으로
// 브라우저 API를 이용하여 문서 타이틀을 업데이트한다.
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
4. Hook의 규칙
· 컴포넌트 최상위에서만 Hook을 호출해야 한다. (반복문, 조건문, 중첩된 함수 내 X)
· 오직 React 함수 내에서 Hook을 호출해야 한다.
5. Hook 코드 연습
// select tag 실행
import React, { useState } from "react";
import "./styles.css";
function SelectExample() {
const [choice, setChoice] = useState("apple");
const fruits = ["apple", "orange", "pineapple", "strawberry", "grape"];
const options = fruits.map((fruit) => {
return <option value={fruit}>{fruit}</option>;
});
const handleFruit = (event) => {
setChoice(event.target.value)
};
return (
<div className="App">
<select onChange={handleFruit}>
{options}
</select>
<h3>You choose "{choice}"</h3>
</div>
);
}
export default SelectExample;
// pop up 실행
import React, { useState } from "react";
import "./styles.css";
function App() {
const [showPopup, setShowPopup] = useState(false);
const openPopup = () => {
setShowPopup(true);
};
const closePopup = () => {
setShowPopup(false);
};
return (
<div className="App">
<h1>Pop Up</h1>
<button className="open" onClick={openPopup}>
Open me
</button>
{showPopup ? (
<div className="popup">
<div className="popup_inner">
<h2>Success!</h2>
<button className="close" onClick={closePopup}>
Close me
</button>
</div>
</div>
) : null}
</div>
);
}
export default App;
'TIL 👩🏻💻' 카테고리의 다른 글
TIL : 스코프 (0) | 2021.08.10 |
---|---|
TIL : Redux (0) | 2021.05.17 |
TIL : Chatterbox Server (0) | 2021.05.04 |
TIL : Mini Node Server (0) | 2021.04.30 |
TIL : Chatterbox Client (0) | 2021.04.29 |