logo
새로운 블로그로 이전하였습니다.

(번역)리액트 19 useActionState 공식 문서 읽어보기

  • react
  • react19
  • hook
  • useActionState

useActionState


useActionState is a Hook that allows you to update state based on the result of a form action.

  • 폼 액션의 결과에 따라 상태를 업데이트하는 훅
  • React Canary 버전의 useFormStateuseActionState로 변경
const [state, formAction, isPending] = useActionState(fn, initialState, permalink?);

Call useActionState at the top level of your component to create component state that is updated when a form action is invoked. You pass useActionState an existing form action function as well as an initial state, and it returns a new action that you use in your form, along with the latest form state and whether the Action is still pending. The latest form state is also passed to the function that you provided.

useActionState를 컴포넌트 최상단에서 호출하면, 폼 액션이 실행됐을 때 업데이트되는 컴포넌트 상태를 만들 수 있습니다. 기존의 폼 액션 함수와 초기 상태를 useActionState에 넘기면, 폼에 사용할 새로운 액션 함수와 최신 폼 상태, 액션이 아직 pending인지 아닌 지를 반환합니다. 가장 최근의 폼 상태는 사용자가 useActionState에 넘겨줬던 폼 액션 함수에도 전달됩니다.

import { useActionState } from "react";
 
async function increment(previousState, formData) {
  return previousState + 1;
}
 
function StatefulForm({}) {
  const [state, formAction] = useActionState(increment, 0);
  return (
    <form>
      {state}
      <button formAction={formAction}>Increment</button>
    </form>
  );
}

The form state is the value returned by the action when the form was last submitted. If the form has not yet been submitted, it is the initial state that you pass. If used with a Server Function, useActionState allows the server’s response from submitting the form to be shown even before hydration has completed.

폼 상태는 폼이 최종으로 submit 됐을 때 액션에 의해 반환되는 값입니다. 폼이 아직 제출되지 않았다면, 폼 상태는 사용자가 초기 상태로 전달한 그 값입니다. 서버 함수랑 함께 사용된다면, useActionState 하이드레이션이 완료되기 전에 폼을 제출해서 받는 서버의 응답이 보여지는게 가능합니다.

Parameters 파라미터

fn: The function to be called when the form is submitted or button pressed. When the function is called, it will receive the previous state of the form (initially the initialState that you pass, subsequently its previous return value) as its initial argument, followed by the arguments that a form action normally receives.

  • fn: 폼이 제출되거나 버튼이 눌렸을 때 호출되는 함수입니다. 함수가 호출되면, 폼의 이전 상태(최초에는 사용자가 전달하는 초기상태, 그 후에는 이전의 반환 상태 값)를 초기 인자로 받습니다. 폼 액션이 보통 받는 인자들을 따릅니다.

initialState: The value you want the state to be initially. It can be any serializable value. This argument is ignored after the action is first invoked.

  • initialState: 초기 상태로 설정하고 싶은 값입니다. 직렬화 가능한 어떤 값이든 가능합니다. 이 인자는 액션이 처음 호출된 후에는 무시됩니다.

optional permalink: A string containing the unique page URL that this form modifies. For use on pages with dynamic content (eg: feeds) in conjunction with progressive enhancement: if fn is a server function and the form is submitted before the JavaScript bundle loads, the browser will navigate to the specified permalink URL, rather than the current page’s URL. Ensure that the same form component is rendered on the destination page (including the same action fn and permalink) so that React knows how to pass the state through. Once the form has been hydrated, this parameter has no effect.

  • optional permalink: 해당 폼이 생성하는 고유한 페이지 URL을 포함하는 문자열입니다. 지속적인 개선으로 주입해줘야하는 동적인 컨텐츠(예: 피드)를 보여주는 페이지에 사용됩니다: fn이 서버 함수이고 폼이 JS 번들이 로드되기 전에 제출된다면, 브라우저는 현재 페이지의 URL이 아닌 특정 permalink URL로 이동시킬 것입니다. 리액트가 어떻게 상태를 전달해야할 지 알 수 있게 같은 폼 컴포넌트(같은 액션 함수와 permalink도 함께)가 대상 페이지에서 렌더링되도록 하세요. 폼이 한 번 하이드레이트 되면, optional permalink는 아무 효과가 없습니다.

반환값

useActionState returns an array with the following values:

useActionState 은 다음의 값들을 포함한 배열을 반환합니다.

  1. The current state. During the first render, it will match the initialState you have passed. After the action is invoked, it will match the value returned by the action.
  1. 현재 상태값: 최초 렌더링동안, 사용자가 전달했던 초기 상태와 매칭됩니다. 액션이 호출된 후에, 액션이 반환한 값과 매칭됩니다.
  1. A new action that you can pass as the action prop to your form component or formAction prop to any button component within the form.
  1. 사용자의 폼 컴포넌트의 action 프롭이나 폼 안에 있는 버튼 컴포넌트의 formAction 프롭으로 전달할 수 있는 새로운 액션
  1. The isPending flag that tells you whether there is a pending Transition.
  1. pending 트랜지션이 있는지를 알려주는 isPending

Usage 사용법

폼 액션이 반환한 정보를 이용하기

Call useActionState at the top level of your component to access the return value of an action from the last time a form was submitted.

폼이 제출됐을 때 마지막으로 실행된 액션의 반환 값에 접근하기 위해 useActionState를 사용자의 컴포넌트의 최상단에서 호출할 수 있습니다.

import { useActionState } from "react";
import { action } from "./actions.js";
 
function MyComponent() {
  const [state, formAction] = useActionState(action, null);
  // ...
  return <form action={formAction}>{/* ... */}</form>;
}

useActionState returns an array with the following items:

useActionState은 다음의 아이템들을 포함한 배열을 반환합니다:

  1. The current state of the form, which is initially set to the initial state you provided, and after the form is submitted is set to the return value of the action you provided.
  1. 폼의 현재 상태 - 초기에는 사용자가 전달한 초기 상태이지만, 폼이 제출된 후에는 사용자가 전달한 액션의 리턴 값으로 설정된 값이 됩니다.
  1. A new action that you pass to <form> as its action prop.
  1. 액션 프롭으로 <form>에 전달하는 새로운 액션
  1. A pending state that you can utilise whilst your action is processing.
  1. 사용자의 액션이 처리되는 동안 활용할 수 있는 pending 상태

When the form is submitted, the action function that you provided will be called. Its return value will become the new current state of the form.

폼이 제출되면, 사용자가 제공한 액션 함수가 호출됩니다. 액션 함수의 반환 값은 폼의 새로운 현재 상태가 됩니다.

The action that you provide will also receive a new first argument, namely the current state of the form. The first time the form is submitted, this will be the initial state you provided, while with subsequent submissions, it will be the return value from the last time the action was called. The rest of the arguments are the same as if useActionState had not been used.

사용자가 제공하는 액션도 새로운 첫 번째 인자, 즉 폼의 현재 상태도 받게 됩니다. 처음에 폼이 제출될 때, 첫 번째 인자는 사용자가 제공한 초기 상태가 되고, 그 이후에는 액션이 마지막으로 호출됐을 때 반환값이 됩니다. 나머지 인자들은 useActionState를 사용하지 않았을 때와 같습니다.

function action(currentState, formData) {
  // ...
  return "next state";
}