constructor() {
this.state = {
count: 0
}
}
와 달리 Hook에서의 state는 객체일 필요가 없다.
import React, { useState } from 'react';
function Example() {
// ...
}
class App extends React.component {
constructor(props) {
super(props)
this.state = {
count: 0
};
}
}
render() {
return (
<div> You clicked {this.state.count} times </div>
<button onClick={() => this.setState({ count: this.state.count + 1 })} </button>
)
}
import React, { useState } from 'react'; // Hook을 React에서 가져온다.
function App() {
const [count, setCount] = useState(초기값);
// Hook을 이용하여 state와 state를 갱신하는 함수 setCount 생성, count 값을 초기 값으로 초기화.
return (
<div> You clicked {count} times </div>
<button onClick{() => setCount(count + 1)}> </button>
// 버튼 클릭 시 setCount 함수 호출하여 state를 갱신
// +1 된 count를 App 컴포넌트에 전달하며 리렌더링.
)
}
class App extends React.component {
conponentDidmount() {
// 컴포넌트 마운트 시 코드 실행.
}
conponentDidUpdate() {
// App data 업데이트 시에 코드 실행.
}
conponentWillmount() {
// 컴포넌트 언마운트 시 clean up
}
}
import React, { useState, useEffect } from 'react';
function App() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = 'You clicked ${count} times'
})
// useEffect(effect)
return (
<div> You clicked {count} times </div>
<button onClick{() => setCount(count + 1)}> </button>
)
}
이러한 복잡성을 줄여주기 위해 상태 관리 라이브러이인 Redux를 사용할 수 있다.