리액트 정리
[Hooks] (in progress) Hooks API Reference (useState, useEffect, useContext, useReducer, useCallback, useMemo, useRef) 본문
리액트
[Hooks] (in progress) Hooks API Reference (useState, useEffect, useContext, useReducer, useCallback, useMemo, useRef)
버그킴 2020. 2. 27. 14:43Hook는 React 16.8에서 새로 추가된 개념입니다. Hook을 통해 class를 작성하지 않고도 state와 같은 React 기능들을 사용할 수 있습니다.
이 페이지는 React에 내장된 Hook API를 설명합니다.
Hook이 생소하다면 Hook 개요를 먼저 읽어 보기 바랍니다. 혹은 frequently asked questions에서 유용한 정보를 찾을 수도 있습니다.
-
- useState : (prevState)=>return [...prevState, newState]
- useEffect : componentDidMount + componentWillUnmount + componentDidUpdate (effect , clean-up, input) input인자 있음
- useContext
-
- useReducer
- useCallback : **함수를 캐싱** Memoization (2) 함수 자체를 기억, 반환 input인자 있음. 자식에 prop으로 함수를 떨궈줄 때. 안걸어주면 자식이 맨날 다른 함수로 prop내리는줄 알고 계속 리렌더링함. 부모로부터 받은 함수가 계속 같구나, 알려주기
- useMemo : **값을 캐싱** Memoization 1 함수의 결과 값을 기억, 반환. input인자 있음
- useRef
- useImperativeHandle
- useLayoutEffect
- useDebugValue
Hooks API Reference – React
A JavaScript library for building user interfaces
ko.reactjs.org
Hooks에 대한 자잘한 팁들:
- 조건문 안에 절대 넣으면 안되고, 함수나 반복문 안에도 웬만하면 넣지 마세요. 무조건 최상위.
- 다른 훅스 안에 다른 훅스를 넣지 마세요. (안되는 예: useEffect안에 useState, useCallback, memo 안에 useState. )
기본 Hook
-
useState
const [state, setState] = useState(initialState);
setState(newState);
function Counter({initialCount}) {
const [count, setCount] = useState(initialCount);
return (
<>
Count: {count}
<button onClick={() => setCount(initialCount)}>Reset</button>
<button onClick={() => setCount(prevCount => prevCount - 1)}>-</button>
<button onClick={() => setCount(prevCount => prevCount + 1)}>+</button>
</>
);
}
setState(prevState => {
// Object.assign would also work
return {...prevState, ...updatedValues};
});
-
useEffect
useEffect(
() => {
// effect - componentDidMount
const subscription = props.source.subscribe();
return () => {
//clean-up - componentWillUnmount
subscription.unsubscribe();
};
},
// condition - componentDidUpdate
[props.source],
);
-
useContext
const value = useContext(MyContext);
추가 Hook
-
useReducer
- useState의 대체함수.
- (state, action) => newState의 형태로 reducer를 받고 / dispatch 메서드와 짝의 형태로 현재 state를 반환
- 다수의 하윗값을 포함하는 복잡한 정적 로직을 만드는 경우나 다음 state가 이전 state에 의존적인 경우에 보통 useState보다 useReducer를 선호
const [state, dispatch] = useReducer(reducer, initialArg, init);
const initialState = {count: 0};
function reducer(state, action) {
switch (action.type) {
case 'increment':
return {count: state.count + 1};
case 'decrement':
return {count: state.count - 1};
default:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
Count: {state.count}
<button onClick={() => dispatch({type: 'decrement'})}>-</button>
<button onClick={() => dispatch({type: 'increment'})}>+</button>
</>
);
}
* 추가 정리 필요
-
useCallback
-
useMemo
-
useRef
'리액트' 카테고리의 다른 글
[UserList] 배열에 항목 추가하기. Spread연산자와 concat (0) | 2020.03.03 |
---|---|
[TodoList] styled-components, createGlobalStyle , Tagged template literal (0) | 2020.03.01 |
[TodoList] 컴포넌트에서 다른 컴포넌트를 담기. 합성 (Composition). {props.children} (0) | 2020.02.29 |
[Router] BrowserRoure, Render props, 동적 라우트, Switch, queryString (0) | 2020.02.29 |
[React] CRA에 Prettier, ESLint, Snippet 끼얹기 (0) | 2020.02.12 |