Skip to main content

Snippets (Serpiko)

About 6 minReact.jsSnippetsjsnodenodejsreactreactjsreactnativefacebookmetasnippets (Serpiko)

Snippets (Serpiko) 관련


react using state when you don't need it

serpiko > react using state when you don't need it

react using state when you don't need it

input 값을 입력받고 보여줄 때, useState를 사용하지 않아도 된다

useState를 배제하므로써, 리렌더링 없앨 수 있다

react using state when you don't need it
import "./styles.css";
import { useState, useRef } from "react";

let renderCount = 0;
export default function App() {
  const emailRef = useRef("");
  const [inputResult, setInputResult] = useState("");

  renderCount++;

  function onSubmit(e) {
    e.preventDefault();
    setInputResult(emailRef.current.value);
    console.log(emailRef.current.value);
  }

  return (
    <>
      <h4>Rerender Count: {renderCount}</h4>
      <form onSubmit={onSubmit}>
        <label htmlFor="email">Email</label>
        <input
          ref={emailRef}
          type="email"
          id="email"
          onChange={() => {
            console.log(emailRef);
          }}
        />
        <button type="submit">Submit</button>
        <p>입력한 텍스트: {inputResult}</p>
      </form>
    </>
  );
}


React Hook Form: FormProvider-useFormContext

serpiko > React Hook Form: FormProvider-useFormContext

React Hook Form: FormProvider-useFormContext
  • ContextAPI를 이용하여 Sub.js에서 사용한 값을 App.js 에서도 감지가 가능하다
React Hook Form: FormProvider-useFormContext
import { useState } from "react";
import { useForm } from "react-hook-form";
import Header from "./Header";
import Sub from "./Sub";
import "./styles.css";
import { useOrderFormContext } from "./FormProviders";

export default function App() {
  const {
    register,
    handleSubmit,
    watch,
    formState: { errors },
  } = useOrderFormContext();

  const [data, setData] = useState("");

  // 등록된 `이름`을 전달하여 입력값을 확인
  // console.log(watch("firstName"));
  // console.log(errors);

  return (
    <div>
      {/* `handleSubmit` 은 onSubmit을 호출하기 전에 입력을 검증 */}
      <form onSubmit={handleSubmit((data) => setData(JSON.stringify(data)))}>
        <Header />
        {/**
         * @description Register fields
         * - `register`함수를 호출하여 입력필드를 훅에 등록하여 값을 관리할 수 있다
         * - 이후에는 이 값으로 유효성 검사, 제출 등의 작업을 할 수 있다
         */}
        <label htmlFor="firstName">[App.js] First Name</label>
        <input
          {...register("firstName")}
          id="firstName"
          placeholder="First name"
        />

        <label htmlFor="lastName">[App.js] Last Name</label>
        {errors.lastName && <span>알파벳만 입력해 주세요</span>}
        <input
          {...register("lastName", { pattern: /^[A-Za-z]+$/i })}
          id="lastName"
          placeholder="Last name (알파벳만 입력해 주세요)"
        />

        <label htmlFor="category">[App.js] category</label>
        <select id="category" {...register("category")}>
          <option value="">Select...</option>
          <option value="A">Option A</option>
          <option value="B">Option B</option>
        </select>

        {/**
         * @description Apply validation
         * - HTML 표준 유효성 검사를 수행하도록 되어있다
         * - required: 필수값 여부
         * - min
         * - max
         * - minLength
         * - maxLength
         * - pattern
         * - validate
         */}
        <label htmlFor="aboutYou">[App.js] aboutYou</label>
        {/* `error` 객체를 사용하여 필듸 유효성 검사에 실패한 경우 오류 메시지를 표시할 수 있다  */}
        {errors.aboutYou && (
          <span>값을 입력해 주세요 (최소5자, 최대 20자)</span>
        )}
        <textarea
          id="aboutYou"
          {...register("aboutYou", {
            required: true,
            minLength: 5,
            maxLength: 20,
          })}
          placeholder="About you (최소5자, 최대 20자)"
        />
        <Sub />
        <p>{data}</p>
        <input type="submit" />
      </form>
    </div>
  );
}


React Hook Form (useState-less 패턴)

serpiko > React Hook Form (useState-less 패턴)

React Hook Form (useState-less 패턴)
  • RHF에 내장된 FormProvider, useOrderFormContext를 이용하여 ContextAPI구현
  • Control을 주입받은 컴포넌트로 모든 컴포넌트는 같은 useForm 생성 시점과 일치 시킨다
  • setValue, resetField, useWatch 이용하여 useState와 리렌더링 없이 양방향 값 핸들링하고 연산
  • 제출(Submit)시, 컴포넌트에 정의된 name 기준으로 값들을 반환한다
React Hook Form (useState-less 패턴)
export default function App() {
  return <h1>Hello world</h1>
}


이찬희 (MarkiiimarK)
Never Stop Learning.