React Hooks

00_8_3·2020년 9월 20일
0

리액트에서 hook이란

hook은 컴포넌트에서 state와 생명주기 기능? 을 연동 해주는 함수이다.

class안에서 동작 하지않고 class없이 리액트를 사용할 수 있게 해준다

(이미 짜놓은 코드 재작성하는 것 권장X)

import React, { useState } from 'react';

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

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

1. useState

useState는 Hook이 제공하는 하나의 라이브러리 입니다.

count라는 현재의 state와 setCount라는 그 값을 업데이트 하는 함수이다

useState(0)이 초기값을 설정한다

{this.state.count} 대신 {count}를 {count: this.state.count +1 } 대신 {count + 1}로 사용할수있다.

2. useEffect

useEffect는 side effect를 사용하게 해준다.
(componentDidmount, componentDidupdate, componentWillUnmount 와 비슷하다)

import React, { useState, useEffect } from 'react';

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

  useEffect(() => {
    document.title = `You clicked ${count} times`;
  });

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

3. useContext

context를 이용하면 단계마다 일일이 props를 넘겨주지 않고도 컴포넌트 트리 전체에 데이터를 제공할 수 있습니다.

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

Context.Provider 사용한다

<MyContext.Provider value={/* 어떤 값 */}>

아직 잘이해 안됨

0개의 댓글