본문 바로가기

POSCO x CODINGOn 웹개발자 양성 부트캠프

[포스코x코딩온] 웹개발자 풀스택 과정 14주차 회고 | React: [React Hook Form, React Context API]

React Hook Form

  • React 애플리케이션에서 폼을 쉽게 관리할 수 있다.
  • 폼의 상태 관리와 유효성 검사를 간단하게 구현할 수 있다.
#설치
npm install react-hook-form

 

주요 키워드

  • register: 입력 요소에 연결하기 위한 함수, 입력 요소에 유효성 검사 규칙을 설정한다.
  • handleSubmit: 폼의 제출을 처리하기 위한 함수, 전달된 콜백은 유효성 검사를 통과한 데이터를 인자로 받아 실행한다.
  • watch: 특정 폼 필드의 값을 실시간으로 관찰하는 함수
  • formState: 폼의 상태를 나타내는 객체 (상태: errors, isValid, isDirty, isSubmitted 등)

 

사용 예제

import { useForm } from 'react-hook-form';

export default function Form() {
	const {
		register,
		handleSubmit,
		formState: { errors },
		watch,
	} = useForm();
	//handleSubmit(): 두개의 함수를 받는데 하나는 폼이 유효할때 실행되는 함수(필수), 하나는 폼이 유효하지 않을때 실행되는 함수(선택)

	const onValid = (data) => {
		console.log('onValid', data);
	};

	// const onInvalid = (error) => {
	// 	console.log('onInvalid', error);
	// };

	console.log('errors', errors);
	// console.log('watch', watch('username'));

	return (
		<>
			<form onSubmit={handleSubmit(onValid)}>
				<input
					type='text'
					{...register('username', {
						required: '이름을 입력하세요',
						minLength: { message: '최소 2글자 이상 작성하세요', value: 2 },
					})}
					placeholder='username'
				/>
				{errors.username?.message}
				<br />
				<input
					type='text'
					{...register('email', {
						required: '이메일을 입력하세요',
						validate: { useGmail: (v) => v.includes('gmail.com') || 'gmail로만 가입가능합니다' },
					})}
					placeholder='email'
				/>
				{errors.email?.message}
				<br />
				<input type='text' {...register('password')} />
				<br />
				<button type='submit'>Submit</button>
			</form>
		</>
	);
}

React Context API

  • React 내장 기능이다.
  • component 트리 전체에 걸쳐 데이터를 공유할 수 있다.
  • 일반적으로 React에서 데이터를 전달하려면 부모 component에서 자식 component에게 props를 통해 전달하지만, 자식 component가 많아질 경우 데이터 관리가 힘들어지는 부분을 보완할 수 있다.
  • 중간 component들을 건너뛰고 데이터를 직접 전달할 수 있다.

 

Context로 주로 전달되는 데이터들

  • 애플리에키션 전체에서 필요한 데이터 (예: 사용자 정보, 테마 및 언어 설정)
  • 여러 component들에 전달되는 반복적인 데이터
  • 전역적인 접근이 필요한 데이터

Context API 사용해 보기

 

createContext

  • createContext(): 설정할 데이터의 type을 정의받고 context 객체를 생성한다.
  • context 값을 보내줄 provider와 해당 context에 접근하기 위한 consumer 두 개의 component를 반환한다.
import {createContext} from "react";

// type 정의 없이 생성
const MyContext = createContext();

// type 정의와 함께 생성
const MyContextWithType = createContext(
	{
		language: '' // string
        age: 0 // number
        changeValue: () => {} //function
    }
);

 

Provider

  • 생성된 context에 값을 제공한다.
  • value prop을 사용하여 값을 전달하고 provider에 의해 제공된 값을 하위 component들이 사용할 수 있다.

Consumer

  • context의 값을 사용하는 방법이다.
  • consumer component 안에 { }를 적어주고 해당 중괄호 안에서 context 값을 받아오고, JSX 문법으로 렌더링 할 요소 및 component를 반환해줄 수 있다.

 

import React, { createContext, useState } from 'react';

//Context생성
//createContext(): Provider와 Consumer 두개의 React Component를 반환

const MyContext = createContext({
	language: '',
	abc: 0,
	setLanguage: () => {},
});



export default function App() {
	// const [language, setLanguage] = useState('ko');

	return (
		<>
			<MyContext.Provider value={{ language: language, setLanguage: setLanguage }}>
				<MyContext.Consumer>
					{(value) => {
						return (
							<div>
								<h2>현재 선택된 언어: {value.language}</h2>
								<select value={value.language} onChange={(e) => value.setLanguage(e.target.value)}>
									<option value='ko'>한국어</option>
									<option value='en'>영어</option>
									<option value='jp'>일본어</option>
								</select>
							</div>
						);
					}}
				</MyContext.Consumer>
			</MyContext.Provider>
		</>
	);
}

 

 

useContext

  • consumer component 보다 더 간결하게 context 값을 가져올 수 있다.
  • consumer component를 사용하지 않고, 렌더링할 함수형 component에서 바로 값을 불러온다.
//다른 폴더에서 정의된 MyContext를 import 하고 아래와 같은 코드로 context 값에 접근할 수 있다.

import {useContext} from 'react';

const value = useContext(MyContext);

 

주의사항

  • 재렌더링의 문제:
    • 특정 component에서 context의 한 부분만 변경할 경우에도 해당 context를 사용하는 모든 component들이 재렌더링된다.
  • 중첩된 provider:
    • 서로 다른 값을 여러 레벨의 component에 전달하려면 provider를 중첩해서 사용해야 하는 경우가 발생할 수 있고 코드의 복잡도가 증가할 수 있다.
  • 전역 상태 관리의 복잡성:
    • 복잡한 애플리케이션에서 전역 상태 관리를 단순히 context API만으로 처리하려고 할 경우, 상태 업데이트 로직이 복잡해질 수 있다.

느낀 점들

React Hook Form 일경우, 사용할 수 있는 옵션들이 너무 많아 필요한 기능이 생길 때 상시 공식문서를 참고할 예정입니다. 추가적으로, 실시간으로 사용자가 입력하고 있는 값이 미리 정의된 규칙에 알맞은지 표시를 하는 기능을 단 코드 몇 줄로 구현할 수 있기에 사용을 한다면 유효성 검사 기능 구현 시간이 상당히 단축될 것 같습니다.

 

Context API는 component끼리 공유할 수 있는 전역 state 같은 개념이라고 이해를 하였고, 불필요한 재렌더링을 방지하려면 정확히 어떤 데이터들이 프로젝트 내에 존재하는 모든 component들이 참조하게 될지 생각해봐야 할 것 같습니다.