리액트는 컴포넌트 생성 전,후 데이터 업데이트 전,후 컴포넌트 제거 등이 이루어질때마다
호출되는 라이프사이클 훅이 있다.
일반적으로 사용되는 라이프 사이클 훅
constructor
컴포넌트 생성 전에 호출되며 컴포넌트의 state를 할당하거나 이벤트를 컴포넌트에 바인딩할 때 사용한다.
constructor 는 먼저 코드를 작성하기 전에 super(props); 를 작성하여 상위클래스의 생성자를 호출 해주어야 한다.
constructor(props) {
super(props);
// Don't call this.setState() here!
this.state = { counter: 0 };
this.handleClick = this.handleClick.bind(this);
}
componentDidMount
컴포넌트를 렌더링 한 직후에 호출되며 이 단계에서 컴포넌트에서 보여줄 데이터들을 가져오는것이 좋다.
componentDidMount() {
console.log('componentDidMount')
}
componentDidUpdate
컴포넌트에서 setState로 컴포넌트의 state가 변경되면 render() 가 다시 호출되어 컴포넌트가 재 렌더링 될때 호출된다.
파라미터인 prevProps, prevState, snapshot 으로 변경되기 이전의 값 들을 조회 해서 비교하는 작업 등을 할 수 있다.
componentDidUpdate(prevProps, prevState, snapshot) {
console.log('componentDidUpdate')
}
componentWillUnmount
컴포넌트가 제거 될 때 호출된다.
setInteval 같은 컴포넌트가 사라지면 유지되어선 안되는 작업들을 이 단계에서 제거 해 주어야 한다.
componentWillUnmount(){
console.log('componentWillUnmount')
}
일반적으로 사용되지 않는 라이프 사이클 훅
shouldComponentUpdate
이 라이프사이클 훅은 state가 변경되어 컴포넌트가 재 렌더링 되기 전에 호출되며
새로운 state가 이전 state와 값이 다른지 비교하여 재 렌더링을 할것인지 말것인지를 결정하는데 사용한다.
성능을 최적화 하는 목적의 용도이며
true를 반환하면 재 렌더링을하고 false를 반환하면 재 렌더링을 하지 않고 이전의 상태를 유지한다.
shouldComponentUpdate(nextProps, nextState) {
console.log('shouldComponentUpdate')
return true
}
getSnapshotBeforeUpdate
컴포넌트가 재 렌더링 할 때 실제로 DOM 을 변경하는 과정이 일어나기 전에 호출되는 라이프 사이클 훅이다.
마지막으로 변경이 일어난 렌더링 시점의 DOM의 정보(width, height 같은)를 스냅샷으로 반환해 줄 수 있다.
이 반환된 스냅샷은 componentDidUpdate 훅에서 매개변수로 전달되어 사용 할 수 있다.
class ScrollingList extends React.Component {
constructor(props) {
super(props);
this.listRef = React.createRef();
}
getSnapshotBeforeUpdate(prevProps, prevState) {
// Are we adding new items to the list?
// Capture the scroll position so we can adjust scroll later.
if (prevProps.list.length < this.props.list.length) {
const list = this.listRef.current;
return list.scrollHeight - list.scrollTop;
}
return null;
}
componentDidUpdate(prevProps, prevState, snapshot) {
// If we have a snapshot value, we've just added new items.
// Adjust scroll so these new items don't push the old ones out of view.
// (snapshot here is the value returned from getSnapshotBeforeUpdate)
if (snapshot !== null) {
const list = this.listRef.current;
list.scrollTop = list.scrollHeight - snapshot;
}
}
render() {
return (
<div ref={this.listRef}>{/* ...contents... */}</div>
);
}
}
componentDidCatch
이 라이프 사이클 훅은 컴포넌트에서 에러 발생시 호출되는 훅이고
에러가 발생했을때 조건부 렌더링으로 에러상황을 대처 할 때 사용한다.
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
componentDidCatch(error, info) {
// Display fallback UI
this.setState({ hasError: true });
// You can also log the error to an error reporting service
logErrorToMyService(error, info);
}
render() {
if (this.state.hasError) {
// You can render any custom fallback UI
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
참고
'React.js' 카테고리의 다른 글
리액트 폼 바인딩 React Form Binding (0) | 2018.07.05 |
---|---|
리액트 리스트 렌더링 React List Rendering (0) | 2018.07.03 |
리액트 state React state (0) | 2018.06.30 |
리액트 props React props (0) | 2018.06.30 |
React 조건부 렌더링 (0) | 2018.06.29 |