ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 리액트 훅 기초 강의(노마드코더 강의 참고)
    프론트엔드/react hook(기초, 노마드코더) 2020. 3. 3. 00:06

    일단 강의에 앞서, 아래 동영상 4개를 먼저 보자. 기초 내용임.

     

     https://www.youtube.com/playlist?list=PL7jH19IHhOLPDyuhF_fLCt_pKvtuLI5qX

     

    React Hooks - YouTube

    All About React Hooks 👉🏻https://academy.nomadcoders.co/p/react-for-beginners

    www.youtube.com

    #1 useState

    1. useState 간단 소개

     

    hook은 함수형이다. 기존 리액트에서 state를 사용하려면 class 기반으로 만들어야 했다. 하지만 hook을 통해 함수형으로 만들었고, 훨씬 적은 코드로 state 변경이 가능하다. 보기도 좋다. (아래는 숫자 증가 감소 구현 코드)

    import React, { useState } from "react";
    import "./styles.css";
    
    const App = () => {
      const [item, setItem] = useState(1);
      const increamentItem = () => setItem(item + 1);
      const decreamentItem = () => setItem(item - 1);
      return (
        <div className="App">
          <h1>Hello {item}</h1>
          <h2>Start editing to see some magic happen!</h2>
          <button onClick={increamentItem}>increamentItem</button>
          <button onClick={decreamentItem}>decreamentItem</button>
        </div>
      );
    };
    
    export default App;
    

     

    2. useInput

     

    -초기값 설정 부분

    useInput에서의 hook의 기본 동작은 const [ value , setValue] = useState(value의 초기값)

    여기서 value의 초기값은 App함수에서 인자로 가지고오는 값이다.

     

    App함수에서 name같은 경우 "Mr." 라는 인자, email은 "@"라는 인자를 넘겨 주고 있다.

    따라서, 해당 인자값이 value의 초기값이 되며 return { value } 를 통해 값을 반환해주고 있다.

     

    해당 값을 이용하기 위해, App함수에서 const name = useInput("Mr.") 라고 정의 하였고

     

    해당 name값을 input 태그 안에 value={name.value}을 지정해줌으로써, 초기값이 해당 value값으로 들어오게 된다.

     

    그렇다면 input 태그안에 값을 입력하려면 어떻게 해야 될까?

     

    onChange를 이용하면 된다. input태그에 있는 value값이 변동이 생길 경우(onChange)

    useInput함수의 onChange 함수가 실행된다. onChange함수 내용은 변화가 감지되는 태그를 지정해주는 event.target을

    이용하여 진행 되는데, 변화 내용은 value가 바뀌는 것이다. 따라서 event.target.value안에 내용이 바뀌게 된다.

    변경되는 value값을 setValue에 넣어준다. (기존 value -> setValue로 state 변경해주는 것임)

     

    최종적으로 return 값에 { onChange } 를 넘겨줌으로써, setValue(value) 값을 넘겨줄 수 있게 된다.

    import React, { useState } from "react";
    import "./styles.css";
    
    const useInput = initialValue => {
      const [value, setValue] = useState(initialValue);
      const onChange = event => {
        const {
          target: { value }
        } = event;
        setValue(value);
      };
      return { value, onChange };
    };
    
    const App = () => {
      const name = useInput("Mr.");
      const email = useInput("@");
      return (
        <div className="App">
          <h1>Hello</h1>
          <input placeholder="name" {...name} />
          <input
            placeholder="email"
            value={email.value}
            onChange={email.onChange}
          />
        </div>
      );
    };
    
    export default App;
    

     

    검증 기능을 넣어보자. 

    import React, { useState } from "react";
    import "./styles.css";
    
    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;
      // const maxLen = value => !value.includes("@");
      const name = useInput("Mr.", maxLen);
      const email = useInput("@", maxLen);
      return (
        <div className="App">
          <h1>Hello</h1>
          <input placeholder="name" {...name} />
          <input
            placeholder="email"
            value={email.value}
            onChange={email.onChange}
          />
        </div>
      );
    };
    
    export default App;
    

    3. useTabs

    버튼을 누르면 content 내용이 바뀌게 하는 기능이다.

    import React, { useState } from "react";
    
    const content = [
      {
        tab: "Section1",
        content: "Im content of section 1"
      },
      {
        tab: "Section2",
        content: "Im content of 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(1, content);
    
      return (
        <div className="App">
          {content.map((section, index) => (
            <button onClick={() => changeItem(index)}>{section.tab}</button>
          ))}
          <div>{currentItem.content}</div>
        </div>
      );
    };
    
    export default App;
    

     

    #2 useEffect

    1. useEffect 간단 소개

     

    useEffect를 통해 didmount, willupdate, unmount를 실행 할 수 있다.

     

    2. useTitle

    import React, { useState, useEffect } from "react";
    
    const useTitle = initialTitle => {
      const [title, setTitle] = useState(initialTitle);
      const updateTitle = () => {
        const htmlTitle = document.querySelector("title");
        htmlTitle.innerText = title;
      };
      useEffect(updateTitle, [title]);
      return setTitle;
    };
    
    const App = () => {
      const titleUpdator = useTitle("Loading...");
      setTimeout(() => titleUpdator("home"), 5000);
      return (
        <div className="App">
          <h1>hello</h1>
        </div>
      );
    };
    
    export default App;
    

    3. useClick

     

    먼저. 훅의 useRef함수에 대한 이해를 하자.

     

    useRef는 getElementgById랑 비슷하다. 해당 태그를 가지고 올 수 있다. 아래 태그 내용이라면, input 부분에 3초 뒤 focus가 실행된다.

     

    import React, { useState, useEffect, useRef } from "react";
    
    const App = () => {
      const potato = useRef();
      setTimeout(() => potato.current.focus(), 3000);
      return (
        <div className="App">
          <h1>hello</h1>
          <input ref={potato} placeholder="hi" />
        </div>
      );
    };
    
    export default App;
    

     

    useClick 코드 내용

    import React, { useState, useEffect, useRef } from "react";
    
    const useClick = onClick => {
      if (typeof onClick !== "function") {
        return;
      }
      const element = useRef();
      useEffect(() => {
        if (element.current) {
          element.current.addEventListener("click", onClick);
        }
        return () => {
          if (element.current) {
            element.current.removeEventListener("click", onClick);
          }
        };
      }, []);
      return element;
    };
    
    const App = () => {
      const sayHello = () => console.log("sayHello");
      const title = useClick(sayHello);
      return (
        <div className="App">
          <h1 ref={title}>hello</h1>
        </div>
      );
    };
    
    export default App;
    

     

    4. useConfirm / usePreventLeave

     

    해당 두개 기능은 hook의 기능과 상관없다. 참조.!

     

    useConfrim 부분

    import React, { useState, useEffect, useRef } from "react";
    
    const useConfirm = (message = "", onConfirm, onCancel) => {
      if (!onConfirm || typeof onConfirm !== "function") {
        return;
      }
      if (onCancel && typeof onCancel !== "function") {
        return;
      }
      const confirmAction = () => {
        if (confirm(message)) {
          onConfirm();
        } else {
          onCancel();
        }
      };
      return confirmAction;
    };
    
    const App = () => {
      const deleteWorld = () => console.log("Deleting the world...");
      const abort = () => console.log("Aborted");
      const confirmDelete = useConfirm("Are you sure?", deleteWorld, abort);
      return (
        <div className="App">
          <button onClick={confirmDelete}>Delete the world</button>
        </div>
      );
    };
    
    export default App;
    
Designed by Tistory.