이챙의 개발 log
React hooks를 class components 대신 사용 해야 하는 이유는 뭘까?
👉React hooks란..?
기존 클래스컴포넌트에서 사용하던 리액트 기능들을 함수컴포넌트에서도 사용할 수 있게 된것 이에요.
함수컴포넌트에서도 state기능을 사용할수 있다! 그걸 hooks라고 불러줘!
이런것이죠
//function components
function App() {
return (
<div>
함수컴포넌트
</div>
);
}
//hooks
const App() => {
const [count, setCount] = useState(0);
return (
<div>
hooks
</div>
);
}
hooks 도입전에 함수컴포넌트는 class 컴포넌트에서 사용하는 state나 라이프사이클을 사용할수 없었어요
return만 가능했죠
그래서 hooks 가 생기면서 함수컴포넌트로도 state와 라이프사이클을 사용할수 있게되었어요
📢우리는 왜 hooks를 사용해야하는 걸까?
그러면 여기서 우리는 의문이 들죠
둘중에 뭐써야하나요?
리액트는 클래스보다 hooks를 권장한다고 합니다!
hooks를 쓰게되면 class component 에서 사용하는 기능을 다 사용할수 있고 코드 줄도 줄어들어요
코드가 줄어든다는건 간결하게 사용가능하다.. 그러면 알게될 개념도 적어지게 된다!
벌써 이유가 다 나온거같네요 우리가 hooks 를 써야할 이유! hooks의 장점!
1. 줄어드는 코드 길이
hooks를 사용하면 class component에 비해 코드길이가 줄어듭니다.
hooks에서는 render를 쓰지 않고 return만 해주면 되니 상대적으로 class 보다 간결해집니다.
// class component
class App extends React.Component {
render() {
return (
<div> class component </div>
);
}
}
// hooks
const App = () => {
return (
<div> class component </div>
);
};
2. useState로 상태관리
클래스 컴포넌트에서 this.state로 상태관리를 했었죠?
hooks에서는 useState로 가능합니다
//class component
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
counter: 0,
};
}
render() {
return (
<>
<p>counter: {this.state.counter}</p>
<button
onClick={() =>
this.setState({
counter: this.state.counter + 1,
})
}
>
클릭!
</button>
</>
);
}
}
// hooks
const App = () => {
const [counter, setCounter] = useState(0);
return (
<>
<p>counter: {counter}</p>
<button onClick={() => setCounter(counter + 1)}>클릭!</button>
</>
);
};
state하나만 사용해도 코드길이가 엄청 차이나죠?
state도 hooks를 사용하면 간결하게 상태관리가 가능합니다.
3. useEffect로 라이프사이클 실행
클래스 컴포넌트에서는 render후 실행되길 원할때 라이프사이클 메소드 중 componentDidmount를 사용하죠
hooks에서는 useEffect로 사용해요.
useEffect를 사용하면 렌더링 후에 실행됩니다.
// class component
class App extends React.Component {
constructor(props){
super(props);
this.state = {
text:"어서오세요!",
}
}
componentDidMount(){
this.timer = setTimeout(()=>{
this.setState({text:"공부하는 공작새에 오신걸 환영합니다"})
},3000)
}
componentWillUnmount(){
clearTimeout(this.timer)
}
render() {
return (
<div> {this.state.text} </div>
);
}
}
// hooks
const App = () => {
const [text,setText] = React.useState("어서오세요!")
React.useEffect(()=>{
const timer = setTimeout(()=>{
setText("공부하는 공작새에 오신걸 환영합니다")
},3000)
return ()=>{
clearTimeout(timer)
}
},[])
return (
<div> {text} </div>
);
};
componentDidmount에서 실행된 이벤트를 제거하려면 componentWillUnmount 도 같이 컴포넌트에 포함시켜줘야 하는데요.
uesEffect에서는 componentWillUnmount대신 return 으로 이벤트를 제거해줍니다.
위 코드에서 보면 알수 있듯이 hooks에서는 useEffect하나로 componentDidmount,componentWillUnmount,componentDidUpdate 의 역할을 모두 수행합니다.
3개의 라이프사이클 메소드를 useEffect 하나로 동일한 역할을 수행한다!
이것은 굉장한 hooks의 이점이라고 생각이 들지않나요?
4. 필요없어진 this
hooks에서는 this가 필요없어요
클래스 컴포넌트에서 여기저기 사용되었던 this의 사용을 더이상 사용하지 않게됩니다.
return (
<Content name="공부하는공작새"/>
);
Content 컴포넌트를 만들어서 props로 name을 전달해볼게요.
// class component
class Content extends React.Component {
constructor(props){
super(props);
this.state = {
text:"어서오세요!",
}
}
render() {
return (
<>
<div> {this.state.text}</div>
<div> {this.props.name} 입니다 </div>
</>
);
}
}
// hooks
const Content = (props) => {
const [text,setText] = React.useState("어서오세요!")
return (
<>
<div> {text} </div>
<div> {props.name} 입니다 </div>
</>
);
};
코드를 봤을때 this 가 무분별하게 있으면 다른사람들이 봤을때 이게 무슨 this인지 혼란을 줄수 있어요
hooks를 사용하면 this에 더이상 바인딩 할일이 없게되죠.
훨씬 보기좋은 코드가 됩니다.
결론
지금 리액트를 클래스를 사용하고 있다면 hooks로 리팩토링을 해보자.
어느것이 더 보기 좋은 코드가 되었는지 비교해보자
'react' 카테고리의 다른 글
useTransition으로 성능 개선하기 (0) | 2024.02.28 |
---|---|
react+webpack+tailwindcss 설치하기! (0) | 2022.09.19 |
useRef props 전달할때 null 값 문제를 forwardRef를 사용하여 해결하기 (0) | 2021.08.12 |
[styled components] class를 추가해서 style을 변경하고 싶을때 props 이용하기(addClass) (0) | 2021.05.31 |
React useEffect 이해해서 사용하기 (0) | 2021.05.19 |
이챙(leechaeng)
프론트엔드 개발도 하고 뛰기도 하고