Hooks
1. ํด๋์คํ ์ปดํฌ๋ํธ์ ํจ์ํ ์ปดํฌ๋ํธ
๊ณผ๊ฑฐ์๋ ๋๋ถ๋ถ์ ์ปดํฌ๋ํธ๋ฅผ ์๋์ ๊ฐ์ด ํด๋์ค ๋ฌธ๋ฒ์ ํ์ฉํ์ฌ ์์ฑํ์์ผ๋, ์ฝ๋๊ฐ ๋ค์ ๊ธธ์ด์ง๊ณ ๋ณต์กํด์ง๋ ๊ฒ์ ์ค์ด๊ธฐ ์ํด ์ต๊ทผ์๋ ํจ์ํ ์ปดํฌ๋ํธ๋ก ์์ฑํ๋ ๋ฐฉ์์ ์ ํธํ๊ณ ์๋ค.
class ๋ฐฉ์์ผ๋ก ์์ฑ๋ Counter ์ปดํฌ๋ํธ
const { useState, memo, Component } = React;
class Counter extends Component {
constructor(props) {
super(props);
// ์ด๊ธฐ ์ํ ์ค์
this.state = {
count: 0
};
}
// ์นด์ดํฐ ์ฆ๊ฐ ํจ์
increment = () => {
this.setState(prevState => ({
count: prevState.count + 1
}));
};
// ์นด์ดํฐ ๊ฐ์ ํจ์
decrement = () => {
this.setState(prevState => ({
count: prevState.count - 1
}));
};
render() {
return (
<div>
<h1>{this.state.count}</h1>
<button onClick={this.increment}>Increase</button>
<button onClick={this.decrement}>Decrease</button>
</div>
);
}
}
ํจ์ํ ๋ฐฉ์์ผ๋ก ์์ฑ๋ Counter ์ปดํฌ๋ํธ
const { useState } = React;
const Counter = () => {
const [count, setCount] = useState(0);
const clickHandler = () => count += 1;
return (
<div>
<p>{count}</p>
<button onClick={clickHandler}>Click me</button>
</div>
)
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Counter />);
2. React Hooks
ํด๋์คํ ์ปดํฌ๋ํธ์์๋ง ์ฌ์ฉ์ด ๊ฐ๋ฅํ๋ ์ํ(state) ๋ฅผ ๊ด๋ฆฌํ๊ฑฐ๋ Ref ๋ฑ์ ํจ์ํ ์ปดํฌ๋ํธ์์๋ ์ฌ์ฉํ ์ ์๋๋ก ๋ฑ์ฅํ ํจ์๋ก, React์์ ์ ๊ณตํ๋ ๋ด์ฅ ํจ์๋ผ๊ณ ๋ณผ ์ ์๋ค.
์ด๋ฌํ Hook์ ํด๋์ค์์ ์ ๊ณต๋๋ ๊ธฐ๋ฅ์ ๊ฐ์ ธ์์ (hooking) ์ฌ์ฉํ๋ค๋ ์๋ฏธ๋ก ๋ค์ด๋ฐ๋๋ค.
function add(a, b) {
useEffect(() => {...}, []); // x
}
*hook์ ์ข ๋ฅ
useState
useEffect
useReducer
์ด ์ ์ ์ฌ์ฉํ ๋ ๋ ๋๋ง์ด ๋ค์ ๋๋ค.
'๊ฐ๋ฐ ์ง์, ์คํฌ๋ฆฝํธ > JavaScript, TS' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
JS Basic Synax(์๋ฃํ) (0) | 2023.12.20 |
---|---|
JS Basic Synax(๋ณ์) (1) | 2023.12.20 |
Props์ State์ ์ฐจ์ด (0) | 2023.12.19 |
State (0) | 2023.12.19 |
Props, Properties (1) | 2023.12.19 |
๋๊ธ