[소플의 처음 만난 리액트] 7장 실습문제

이 문서는 리액트와 관련된 여러 실습 예제들을 다루고 있습니다. 주요 내용으로는 useRef를 이용한 DOM 요소 포커스, useEffect를 이용한 사이드 이펙트 처리, 커스텀 훅을 이용한 컴포넌트 개발 등이 있습니다.
Dec 30, 2023
[소플의 처음 만난 리액트] 7장 실습문제

TextInputWithFocusButton.jsx

import React, { useRef } from "react"; function TextInputWithFocusButton(props) { const inputElem = useRef(null); const onButtonClick = () => { // current는 마운트된 input element를 가리킴 inputElem.current.focus(); }; return ( <> <input ref={inputElem} type="text" /> <button onClick = {onButtonClick} >Focus the input</button> </> ); } export default TextInputWithFocusButton;
 

핵심 키워드

  • useRef를 이용해서 버튼을 클릭시 focus 시킬 DOM 요소를 직접 선택할 수 있다.
 

Counter.jsx

import React, { useState, useEffect } from "react"; function Counter(props) { const [count, setCount] = useState(0); //컴포넌트 내에서 직접 메타 태그를 변경해서는 안된다. side effect는 컴포넌트의 렌더링에 방해가 된다. // componentDidMount, componentDidUpdate와 비슷하게 작동 useEffect(() => { // 모든 컴포넌트가 업데이트 될 때마다 호출. // 브라우저 API를 사용해서 document의 title을 업데이트 document.title = `총 ${count}번 클릭했습니다.`; }); return ( <div> <p>총 {count}번 클릭했습니다.</p> <button onClick={() => setCount(count + 1)}> 클릭 </button> </div> ) } export default Counter;

MeasureExample.jsx

import React, {useState, useCallback} from "react"; function MeasureExample(props){ const [height, setHeight] = useState(0); const measuredRef = useCallback(node => { if(node !== null){ setHeight(node.getBoundingClientRect().height); } },[]); return( <> <h1 ref={measuredRef}>안녕, 리액트</h1> <h2>위 헤더의 높이는 {Math.round(height)}px 입니다.</h2> </> ); } export default MeasureExample;

핵심 키워드

  • useEffect 함수는 컴포넌트가 마운트, 업데이트, 언마운트 되는 특정 시점에 특정 작업을 실행할 수 있게 하는 훅이다.
  • 기존에 클래스형 컴포넌트에서 사용하지 못했던 생명주기 메소드를 훅을 이용해 함수형 컴포넌트에서 사용할 수 있다.
 

useCounter.jsx

import { useState } from "react"; function useCounter(initialValue) { const [count, setCount] = useState(initialValue); const increaseCount = () => setCount((count) => count + 1); const decreaseCount = () => setCount((count) => Math.max(count - 1, 0)); return [count, increaseCount, decreaseCount]; } export default useCounter;

Accommodate.jsx

import React, { useState, useEffect } from "react"; import useCounter from "./useCounter"; // 훅을 사용한 컴포넌트 개발 const MAX_CAPACITY = 10; function Accommodate(props) { const [isFull, setIsFull] = useState(false); const [count, increaseCount, decreaseCount] = useCounter(0); // state 두개 선언 useEffect(() => { console.log("============================"); console.log("useEffect() is called"); console.log(`isFull: ${isFull}`); }); // isFull count 두개의 state에 반응 useEffect(() => { // MAX_CAPACITY에 도달하면 setIsFull이 True. setIsFull(count >= MAX_CAPACITY); console.log(`Current count value: ${count}`); },[count]); // count state에만 반응 return( <div style={{padding: 16}}> <p>{`총 ${count}명 수용했습니다.`}</p> <button onClick={increaseCount} disabled={isFull}> 입장 </button> <button onClick={decreaseCount}>퇴장</button> {isFull && <p style={{color: "red"}}>정원이 가득찼습니다.</p>} {/* isfull이 ture일 경우 실행 */} </div> ); } export default Accommodate;
 

핵심 키워드

  • 사용자가 기존의 훅들을 이용해 커스텀 훅을 생성해서 컴포넌트를 개발할 수 있다.
  • 커스텀 훅을 사용하는 가장 큰 이유는 반복되는 로직을 하나로 묶어 재사용하기 위함이다.
  • 커스텀 훅을 이용해 만든 기능은 각각의 컴포넌트에서 독립된 상태를 가진다.
 

결론!

훅이란 무엇인지, 훅의 규칙과 커스텀 훅을 이용한 컴포넌트 개발의 중요성에 대해 이해할 수 있었다.
Share article

More articles

See more posts
RSSPowered by inblog