TIL: 2022-06-04 React 심화

김하연·2022년 6월 4일
0

TIL: Today I Leaned

목록 보기
21/26

Custom Hook

계속해서 반복 사용되는 이벤트를 반복 사용할 수 있도록 Hook 으로 만드는 것.

  • 규칙
    이름은 use~ 로 시작해야 한다. ex) useClickevent, useCompletes...
    반드시 return 값이 있어야 한다.

  • 주의사항
    Custom hook에서 만든 state가 전역 state가 아니다.
    예를 들어 custom hook을 componenet A에서 불러서 쓰게되면 component A에만 존재하는 state가 되는 것이다. 그렇기 때문에 state값이 컴포넌트 간에 공유가 되어야 한다면 부모 컴포넌트에서 import 하고 props로 넘겨줘야 한다.

// App.js

import React, { useRef } from 'react';

import {Textbox, Input, Button} from './Components';
import useSetText from './useSetText';

function App() {
  const [text, setText] = useSetText('');
  const input_ref = useRef();
  return (
		<div className="App" style={{display: 'flex', gat: 10, padding: '60px'}}>
			<div>
				<Textbox text={text}></Textbox>
			</div>
			<div>
				<Input input_ref={input_ref}></Input>
				<Button input_ref={input_ref} setText={setText}>입력</Button>
			</div>
		</div>
	);
}

export default App;
// Components.js

import React from 'react';

export const Textbox = ({text}) => {
  return (
    <div style={{border:'1px solid #ddd', width: '300px', minHeight: '200px'}}>
      <p>{text}</p>
    </div>
  );
}

export const Input = ({input_ref}) => {
  return (
    <input type="text" ref={input_ref}/>
  )
}

export const Button = ({input_ref, setText}) => {
  return <button type="button" onClick={()=>{
    setText(input_ref);
  }}>추가하기</button>
}
// useSetText.js

import {useState} from 'react';

const useSetText = (initial = '') => {
  const [text, setText] = useState(initial);
  const changeText = (_ref) => {
    setText(_ref.current.value);
    _ref.current.value = '';
  }
  return [text, changeText];
}

export default useSetText;

0개의 댓글