React Hooks (1)

dorazi·2021년 1월 28일
0

React

목록 보기
2/3
post-thumbnail

계속 클래스 컴포넌트나 함수형 컴포넌트만 사용하다보니 Hooks가 절실하게 느껴지는거 같다.
Hooks의 생태계는 이미 엄청 많은 라이브러리들이 오픈소스로 공개되어있어서 사용하지 않은면 오히려 손해 같은 느낌이 들어서 이번에 Hooks를 좀 더 깊게 파보려한다

Hooks

hooks를 사용하면 좋은 점은 먼저 상태관리를 위한 클래스 컴포넌트, Did mount, render 등을 안해도되고 모든것이 하나의 함수로 작성된다는 것이다.

Hooks의 역사

Hooks의 역사는 recompose부터 시작되었다고 한다. recompose 라이브러리 제작자가 react 팀으로 가게되면서 React-Hooks가 탄생되었다고한다.

useState

useState는 항상 2개의 value를 return 한다.

const [value1 , value2] = useState('초기값')

이런식으로 작성할 수 있고 value1은 초기값의 현재값을 가지고있고 value2를 이용해 value1을 변경할 수 있다. value2가 setState와 같은 기능이라고 생각하면 좀 이해가 쉬울듯 하다.

예시로

const [count, setcount] = useState(0)

const increment = () => setcount(count + 1)

return (
<>
 <h1>현재 숫자는 {count}</h1> 
<button onClick={increment}></button>
</>
)

위와 같이 작성을 한다면 버튼을 통해 count의 값을 변경할 수 있다.

useInput

useInput은 useState를 응용한 커스텀 Hooks다.

const useInput = (initialValue, validator) => {
  const [value, setValue] = useState(initialValue);
  const onChange = (event) => {
    const {
      target: { value }
    } = event;
    let willUpdate = true;
    if (typeof validator === "function") {
      willUpdate = validator(value);
    }
    if (willUpdate) {
      setValue(value);
    }
  };
  return { value, onChange };
};

export default function App() {
  const maxLen = (value) => value.length <= 10;
  const name = useInput("Mr.", maxLen);
  return (
    <div className="App">
      <h1>Hello</h1>
      <input placeholder="Name" value={name.value} onChange={name.onChange} />
    </div>
  );
}

useTabs

useTabs는 버튼에 따라 컨텐츠가 랜더링되는 커스텀 Hooks다 이또한 useState를 사용한다.

const content = [
  {
    tab: "Section 1",
    content: "I'm the content of the Section 1"
  },
  {
    tab: "Section 2",
    content: "I'm the content of the Section 2"
  }
];

const useTabs = (initialTab, allTabs) => {
  if (!allTabs || !Array.isArray(allTabs)) {
    return;
  }
  const [currentIndex, setCurrentIndex] = useState(initialTab);
  return {
    currentItem: allTabs[currentIndex],
    changeItem: setCurrentIndex
  };
};

const App = () => {
  const { currentItem, changeItem } = useTabs(0, content);
  return (
    <div className="App">
      {content.map((section, index) => (
        <button onClick={() => changeItem(index)}>{section.tab}</button>
      ))}
      <div>{currentItem.content}</div>
    </div>
  );
};
profile
프론트엔드 개발자

0개의 댓글