[TIL #57] Hooks란?

Whoyoung90·2021년 6월 2일
0
post-thumbnail

> 클래스형 vs 함수형 컴포넌트의 차이?

클래스형

  • state 및 LifeCycle API를 사용
  • Component에서 상속(extends)받아야 한다.
  • render 함수가 꼭 있어야 하고 JSX를 반환해야 한다.
class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
      ismodalOn: false,
    };
  }

  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와 LifeCycle API를 사용할 수 없다는 단점이 있었는데, 리액트 hook이 도입되면서 해결!

  • 클래스형 컴포넌트보다 선언하기 편하고 메모리 자원을 덜 사용하는 장점

function Example() {
  const [count, setCount] = useState(0);
  const [isModalOn, setIsModalOn] = useState(false);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
      <button onClick={() => setIsModalOn(!isModalOn)}>modal btn</button>
    </div>
  );
}

> Hooks 란?

함수형 컴포넌트에서 state와 LifeCycle API를 사용할 수 없는 단점을 해결!

Hook은 함수형 컴포넌트에서 상태값을 관리하고(useState),
Lifecycle 메서드를 사용(useEffect) 할 수 있게 해주는 함수이다.

State Hook (useState)

const [state, setState] = useState(initialState);

Effect Hook (useEffect)

useEffect(() => {
	console.log("componentDidMount")
	return () => console.log("componentWillUnmount")
}, []) // 더 이상 감지하는 state가 없으므로 한번 실행되고 그 이후에는 실행되지 않음

useEffect(() => {
	console.log("componentDidMount + componentDidUpdate")
}) // 타이밍 정해주지 않았으므로 매 render마다 실행됨

useEffect(() => {
	console.log("componentDidMount")
	console.log("componentDidUpdate") // + shouldComponentUpdate
	return () => console.log("???")
}, [state]) // 최초 렌더도 되고~ state값이 변경될때마다 불러오고~

///

useEffect(() => {
	console.log("componentDidMount")
	return () => console.log("componentWillUnmount")
}, []) 
// setInterval-clearInterval, addEventListener-removeEventListener

Custom Hook

useState, useEffect 등 다양한 내장 Hook 등을 조합하면 반복되는 로직을 분리해 Custom Hook을 작성할 수 있다.

profile
비전공으로 일식 쉐프가 되었듯, 배움에 겸손한 프론트엔드 개발자가 되겠습니다 :)

0개의 댓글