카테고리 없음
리액트 hooks useState 예제들로 파악해보자
카쿤개발자
2020. 11. 6. 04:20
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>
</>
);
}
같은 코드를 class 형태로 표현
import React, { useState } from 'react';
function Example() {
// 새로운 "count"라고 부르는 state 변수를 선언
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Click me
</button>
</div>
);
}
}
조금 심화한 응용 예제:
여러개의 state를 사용하기
함수형 컴포넌트는 useState()를 여러번 작성하여 필요한 수 만큼의 states를 가질 수 있다.
function MyComponent() {
const [state1, setState1] = useState(initial1);
const [state2, setState2] = useState(initial2);
const [state3, setState3] = useState(initial3);
// ...
}
import React, { useState } from 'react';
function Bulbs() {
const [on, setOn] = useState(false);
const [count, setCount] = useState(1);
const lightSwitch = () => setOn(on => !on);
const addBulbs = () => setCount(count => count + 1);
const bulb = <div className={on ? 'bulb-on' : 'bulb-off'} />;
const bulbs = Array(count).fill(bulb);
return (
<>
<div className="bulbs">{bulbs}</div>
<button onClick={lightSwitch}>On/off</button>
<button onClick={addBulbs}>Add bulb</button>
</>
);
}
참조: reactjs.org/docs/hooks-state.html
Using the State Hook – React
A JavaScript library for building user interfaces
reactjs.org
dmitripavlutin.com/react-usestate-hook-guide/#1-state-management-using-usestate
The Wise Guide to React useState() Hook
React useState() hook manages the state of functional components.
dmitripavlutin.com