[react] Hooks

Kyungoh Kang·2020년 12월 30일
0

wecode15

목록 보기
18/20

Hooks = 함수

설명

  1. 클래스형 컴포넌트에서는 this를 사용하는 경우가 많은데 여러 문제를 발생 시킨다.
    -> 예시 링크
  2. Class는 사람과 기계를 혼동시킨다.
  3. 클래스에서 발생하는 여러 문제들을 해결하기 위해 hooks가 개발되었다.
  4. 기존 클래스로 작성된 코드들과 100% 호환되기 때문에 기존 코드들을 수정할 필요가 없다.

hooks 규칙

  1. 최상위에서만 hooks를 호출해야한다. 그리고 반복문, 조건문, 중첩된 함수 내에서 실행할 수 없다.

  2. react 함수 컴포넌트 내에서만 hooks를 호출해야 한다.

state hooks

  1. useState
const [state, setState] = useState( state초기값 );
  • useState 원리
// 아주 간단한 버전의 useState

const useState = (init = undefined) => {
  let value = init

  const getter = () => value // 클로저
  const setter = next => (value = next) // 클로저

  return [getter, setter]
}

const [state, setState] = useState('클로저')

state()
setState("어려워!")
state()

//state는 getter, setState는 setter 역할로 useState가 반환하는 [getter, setter]를 비구조화 할당 해준 것임.
  • 하나의 state에 여러 관련 없는 값들을 한번에 넣어주는 것은 좋지 않다.
const [state, setState] = useState({
	color: red,
  	name: "",
  	isActive: true,
}) // 좋지 않은 예
  • 데이터를 받아오는 스테이트를 만들 때는 괜찮음.

effect hooks

  1. 함수 컴포넌트 내에서 여러 side effects를 수행할 수 있게 해주는 훅.(componentDidMount, comcponentDidUpdate, componentWillUnmount 이 셋을 하나의 api로 통합)

  2. 코드 예시

useEffect(() => {
	console.log("componentDidUpdate")
})

useEffect(() => {
	console.log("componentDidMount")
	return () => console.log("componentWillUnmount")
}, [])

useEffect(() => {
	console.log("componentDidMount")
	console.log("componentDidUpdate") // + shouldComponentUpdate
	return () => console.log("???")
}, [state])

//의존배열 내에 값이 있으면 그 값을 참조하여 값이 변경 될 때마다 useEffect가 실행이 된다.

// 두번째에서 compDidMount에 조건문을 걸어주면 compDidUpdate만 실행시켜줄 수 있다.

custom hook

=> 나중에 공부하기

0개의 댓글