React life cycle은 크게 3가지 유형으로 나뉜다.
각 life cycle에는 method가 있고, method 간에는 실행 순서가 존재한다.
이번 글에서는 life cycle의 유형을 method 실행 순서에 따라 정리해 보았다.
// Class
class Example extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
// Hooks
const Example = () => {
const [count,setCount] = useState(0);
}
// Class
class Example extends React.Component {
static getDerivedStateFromProps(nextProps, prevState) {
if (nextProps.value !== prevState.value) {
return { value: nextProps.value }
}
return null
}
}
// Class
class Example extends React.Component {
render() {
return <div>컴포넌트</div>
}
}
// Hooks
const example = () => {
return <div>컴포넌트</div>
}
// Class
class Example extends React.Component {
componentDidMount() {
...
}
}
// Hooks
const Example = () => {
useEffect(() => {
...
}, []);
}
// Class
class Example extends React.Component {
shouldComponentUpdate(nextProps) {
return nextProps.value !== this.props.value
}
}
// Hooks
const Example = (props) => {
const { value } = props
return ( <Component/> )
}
const areEqual = (prevProps , nextProps) => {
return prevProps.count === nextProps.count
}
export default React.memo(Example , areEqual)
)
// Class
class Example extends React.Component {
getSnapshotBeforeUpdate(prevProps, prevState) {
if (prevProps.list.length < this.props.list.length) {
const list = this.listRef.current
return list.scrollHeight - list.scrollTop
}
return null
}
}
// Class
class Example extends React.Component {
componentDidUpdate(prevProps, prevState) {
...
}
}
// Hooks
const Example = () => {
useEffect(() => {
...
});
}
// Class
class Example extends React.Component {
componentWillUnmount() {
...
}
}
// Hooks
const Example = () => {
useEffect(() => {
return () => {
...
}
}, []);
}