리액트/Hooks

ch07.커스텀 Hooks 만들기

webmaster 2021. 11. 16. 22:52
728x90
  • 여러 컴포넌트에서 비슷한 기능을 공유할 경우 커스텀 Hook으로 로직을 재사용할 수 있다.
  • import { useReducer } from "react";
    
    function reducer(state, action) {
      return {
        ...state,
        [action.name]: action.value,
      };
    }
    export default function useInputs(initialForm) {
      const [state, dispatch] = useReducer(reducer, initialForm);
      const onChange = (e) => {
        dispatch(e.target);
      };
      return [state, onChange];
    }
  • import React, { useEffect, useState, useReducer } from "react";
    import useInputs from "./useInputs";
    const Info = () => {
      const [state, onChange] = useInputs({
        name: "",
        nickname: "",
      });
      const { name, nickname } = state;
      return (
        <div>
          <div>
            <input name="name" value={name} onChange={onChange} />
            <input name="nickname" value={nickname} onChange={onChange} />
          </div>
          <div>
            <div>
              <b>이름:</b> {name}
            </div>
            <div>
              <b>닉네임:</b>
              {nickname}
            </div>
          </div>
        </div>
      );
    };
    export default Info;

다른 Hooks

 

Collection of React Hooks

 

nikgraf.github.io

 

GitHub - rehooks/awesome-react-hooks: Awesome React Hooks

Awesome React Hooks. Contribute to rehooks/awesome-react-hooks development by creating an account on GitHub.

github.com

 

728x90

'리액트 > Hooks' 카테고리의 다른 글

ch06.useRef  (0) 2021.11.16
ch05.useCallback  (0) 2021.11.16
ch04.useMemo  (0) 2021.11.16
ch03.useReducer  (0) 2021.11.15
ch02.useEffect  (0) 2021.11.15