프론트엔드/React

React hook

테오구 2021. 10. 2. 17:08
728x90

useState

상태 유지값과 그 값을 갱신하는 함수를 반환합니다.

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

usestate의 초기값은 initialstate이며 setState를 사용해 state를 갱신해 줍니다.

지연 초기 state

initialState인자는 초기 렌더링 시에 사용하는 state 초기 state가 고비용 계산이라면 초기 렌더링 시에만 실행될 함수를  대신 제공

 

 

useEffect

 

명령 또는 어떠한 effect를 발생하는 함수를 인자로 받습니다.

 

useEffect는 브라우저 화면이 다 그려질 때까지 지연됩니다만, 다음 어떤 새로운 렌더링이 발생하기 이전에 발생하는 것도 보장합니다. React는 새로운 갱신을 시작하기 전에 이전 렌더링을 항상 완료하게 됩니다.

 

조건부 effect

 

기본적으로 useEffect는 처음 렌더링이 될 때마다 useEffect가 사용되지만 조건부를 source props만 변경해준다면 source props만이 변경될 때만 useEffect가 사용됩니다.

 

useEffect(() => {
  const subscription = props.source.subscribe();
  return () => {
    // Clean up the subscription
    subscription.unsubscribe();
  };
});
useEffect(
  () => {
    const subscription = props.source.subscribe();
    return () => {
      subscription.unsubscribe();
    };
  },
  [props.source],
);

 

 

useContext

 

context 객체(React.createContext에서 반환된 값)을 받아 그 context의 현재 값을 반환합니다. context의 현재 값은 트리 안에서 이 Hook을 호출하는 컴포넌트에 가장 가까이에 있는 <MyContext.Provider> value prop에 의해 결정됩니다.

 

컴포넌트에서 가장 가까운 <MyContext.Provider>가 갱신되면 이 Hook은 그 MyContext provider에게 전달된 가장 최신의 context value를 사용하여 렌더러를 트리거 합니다. 상위 컴포넌트에서 React.memo 또는 shouldComponentUpdate를 사용하더라도 useContext를 사용하고 있는 컴포넌트 자체에서부터 다시 렌더링됩니다.

 

const themes = {
  light: {
    foreground: "#000000",
    background: "#eeeeee"
  },
  dark: {
    foreground: "#ffffff",
    background: "#222222"
  }
};

const ThemeContext = React.createContext(themes.light);

function App() {
  return (
    <ThemeContext.Provider value={themes.dark}>
      <Toolbar />
    </ThemeContext.Provider>
  );
}

function Toolbar(props) {
  return (
    <div>
      <ThemedButton />
    </div>
  );
}

function ThemedButton() {
  const theme = useContext(ThemeContext);
  return (
    <button style={{ background: theme.background, color: theme.foreground }}>
      I am styled by theme context!
    </button>
  );
}

 

useReducer

const [state, dispatch] = useReducer(reducer, initialArg, init);

useState의 대체 함수 입니다. reducer를 받고 dispatch 메서드와 짝의 형태로 현재 state를 반환합니다.

 

다수의 하윗값을 포함하는 복잡한 정적 로직을 만드는 경우나 다음 state가 이전 state에 의존적인 경우에 보통 useState보다 useReducer를 선호합니다.

 

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>
    </>
  );
}

useState를 reducer로 다시 작성한 것

 

 

useMemo

메모이제이션(컴퓨터 프로그램이 동일한 계산을 반복해야 할 때, 이전에 계산한 값을 메모리에 저장함으로써 동일한 계산의 반복 수행을 제거하여 프로그램 실행 속도를 빠르게 하는 기술이다. 동적 계획법의 핵심이 되는 기술)된 값을 반환합니다.

 

useMemo는 의존성이 변경되었을 때에만 메모이제이션된 값만 다시 계산 할 것입니다. 이 최적화는 모든 렌더링 시의 고비용 계산을 방지하게 해 줍니다.

 

useMemo로 전달된 함수는 렌더링 중에 실행된다

 

useRef

useRef .current 프로퍼티로 전달된 인자(initialValue)로 초기화된 변경 가능한 ref 객체를 반환합니다.

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>
    </>
  );
}

 

728x90

'프론트엔드 > React' 카테고리의 다른 글

Effect Hook  (0) 2021.10.20
Side Effect  (0) 2021.10.20
React State & Props  (0) 2021.09.27
Router  (0) 2021.09.17
SPA  (0) 2021.09.16