React Hooks -2
1.useContext (뭐야;) Context의 개념 확인
• 사용법
const value = useContext(MyContext) // 인자는 context 객체 그 자체여야 함
=== static contextType = MyContext 또는 <MyContext.Consumer>
- context객체를 받아 그 context의 현재 값을 반환한다.
- context의 현재 값은 트리 안에서 이 Hooks를호출하는 컴포넌트에 가장 가까이 있는
<MyContext.Provider>의 value props에 의해 결정됨
- 가장 가까운 <MyContext.Provider>가 갱신되면 MyContext provider에 전달된 가장 최신의
context valued를 사용하용하여 렌더러를 트리거 합니다.
useContext를 사용하고 있는 컴포넌트 자체부터 다시 렌더링 함
2. useReducer 이건 Redux개념과 같이 파악
• 사용법
1. 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();
}
}
const [state,dispatch] = useReducer(reducer,initialState); // 선언
<button onClick ={() => dispatch({type :'decresment'})}> - </button>
2. const [state, dispatch] = useReducer( reducer, {count: initialCount} );
- useState의 대체 함수 (state,action) => newState 형태로 reducer를 받고 dispatch 메서드와 짝의 형태로 현재 state를 반환, Redux의 개념과 비슷
- 다수의 값을 포함하는 로직을 만들 경우나 다음 state가 이전 state에 의존적인 경우 선호
- 초기 state를 조금 지연하여 생성할려는 경우 init 함수 선언 후 세번째 인자로 전달
3.useCallback
• 사용법
const memoizedCallback = useCallback({
() => {
doSomething(a,b);
},
[a,b],
}
메모이제이션(memoization) : 동일한 계산을 반복할 때 이전에 계산한 값을 메모리에 저장 함으로써 반복 수행을 제거하여 프로그램 실행 속도를 빠르게 하는 기술
- 메모이제이션된 콜백을 반환
- useCallback(fn,deps) 은 useMemo(()=> fn,deps) 와 동일
4.useMemo
• 사용법
const memoizedValue = useMemo(()=> computeExpensiveValue(a,b) ,[a,b]);
- useMemo는 의존성이 변경되었을 때에만 메모이제이션된 값만 다시 계산
- useMemo로 전달된 함수는 렌더링 중에 실행 됨
- 렌더링 중에는 하지 않는 것을 이 함수 내에서 하지 마시오 EX) 사이드 이펙트는 useEffect에서!
5.useRef
• 사용법
const refContainer= useRef(intialValue);
function TextInputWithFocusButton()
{
const inputEl = useRef(null);
const onButtonClick = () => { // `current` points to the mounted text input element
inputEl.current.focus(); };
return (
<>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</> );
}
- useRef는 .current 프로퍼티로 전달된 인자(initialValue)로 초기화된 변경 가능한 ref 객체를 반환
5. useLayoutEffect
- 사용법 useEffect 와 동일
- DOM 변경 후에 동기적으로 발생, DOM에서 레이아웃을 읽고 동기적으로 리렌더링 하는 경우에 사용하시오