3.실전형 리액트 Hooks 10개

2 minute read

1.0 Introduction to Nooks

  • Hook을 사용하는 이유

    Hook을 이용하여 Class를 작성할 필요 없이 상태 값과 여러 React의 기능을 사용할 수 있습니다. 다시말해 함수형 컴포넌트에서도 state를 수정할수 있다 !!

1.1 Requirements

1.2 Workflow

2.0 Introduction to useState

useState

  • (1). useState 사용하지 않았을때
class App extends React.Component {
  state = {
    count: 0,
  };

  add = () => {
    this.setState({
      count: this.state.count + 1, //좋은 코딩은 아니다. why? 외부에서 state를 의존하기 때문에 좋은방법이 아니다.
    });
  };

  minus = () => {
    this.setState((current) => ({
      //current = this.state
      count: current.count - 1, //좋은 코딩이다.
    }));
  };

  render() {
    return (
      <div>
        <h1>The number is {this.state.count}</h1>
        <button onClick={this.add}>Add</button>
        <button onClick={this.minus}>Minus</button>
      </div>
    );
  }
}
  • (2). useState 사용했을때
import React, { useState } from "react";

import "./styles.css";

function App() {
  const [item, setItem] = useState(1);

  const incrementItem = () => setItem(item + 1);

  const decrementItem = () => setItem(item - 1);

  return (
    <div className="App">
      <h1>Hello {item}</h1>
      <button onClick={incrementItem}>Increment</button>
      <button onClick={decrementItem}>Decrement</button>
    </div>
  );
}

export default App;

2.1 useInput (cutomize)

  • (1). useInput 사용하지 않았을때 : input의 value값만 바꿔주는 용도로만 사용할껀데 그게 100개의 컴포넌트에 필요하다면 useInput처럼 customize하지 않고 아래코드처럼 사용한다면 100개 컴포넌트의 input마다 onchange를 해주고 useState를 해줘야하니까 코드를 많이 쓰므로 좋지않은 방법이다.
import React, { useState } from "react";

function App() {
  const [inputs, setInputs] = useState(0);

  const onChange = (e) => {
    const a = e.target.value;

    setInputs(a);
  };

  return (
    <div>
      <h1>Hello</h1>
      <input
        placeholder="Name"
        onChange={(e) => onChange(e)}
        value={inputs}
      ></input>
    </div>
  );
}

export default App;
  • (2). useInput 사용했을때 : useInput을 사용하는 이유는 , 기본적으로 input만을 업데이트 하기 위해 사용된다. 그리고 이렇게 할경우 재활용해서 사용할수 있기 때문에 단순히 input의 value값만 바꿔주기 위한 용도로 사용한다면 이렇게 함수로 작성하고 여러군데서 재활용해서 사용하면 좋을것 같다.
import "./styles.css";
import { useState } from "react";

// 함수
const useInput = () => {
  const [value, setValue] = useState();

  const onChange = (event) => {
    setValue(event.target.value);
  };

  return { value, onChange };
};

const App = () => {
  const name = useInput();

  return (
    <div>
      <h2>Hello</h2>
      <input placeholder="Name" {...name} />
    </div>
  );
};

export default App;

2.2 useInput part Two (useInput에 유효성기능 추가,customize)

10자리 이상 입력 안돼게 수정함

import "./styles.css";
import { useState } from "react";

// 함수
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 };
};

const App = () => {
  const maxLen = (value) => value.length < 10; //10자리 이상 안되게 함
  const name = useInput("Mr..", maxLen);

  return (
    <div>
      <h2>Hello</h2>
      <input placeholder="Name" {...name} />
    </div>
  );
};

export default App;

2.3 useTabs


3.1 Introduction to useEffect

3.2 useTitle

3.3 useClick

3.4 useConfirm & usePreventLeave

3.5 useBeforeLeave

3.6 useFadeIn & useNetwork

3.7 useScroll & useFullscreen

3.8 useNotification

3.9 useAxios

3.10 Conclusions

3.11 Publishing to NPM

3.12 What to learn next

Tags:

Categories:

Updated:

Leave a comment