#useActionState initialValue

1 messages · Page 1 of 1 (latest)

magic tartanBOT
#

Hi @leaden ivy. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Based on the knowledge sources provided, there seems to be an issue with useActionState not updating the initial value as expected. This behavior appears to be a known problem in Next.js.

According to a GitHub issue (https://github.com/vercel/next.js/issues/68549), after a successful form submission and redirect, the action state becomes undefined despite having an initial value provided. The expected behavior would be for the action state to return to the initial state after a successful submission.

Unfortunately, the knowledge sources don't provide a direct solution for updating the initial value in useActionState. However, there are a couple of workarounds you might consider:

  1. Use useFormState instead: As mentioned in another GitHub issue (https://github.com/vercel/next.js/issues/65673), you can use useFormState from react-dom as an alternative to useActionState. This might help resolve the issue with the initial value not updating.

  2. Create a custom hook: One user suggested creating a custom hook to handle the state updates. Here's an example of such a hook:

const useResettableActionState = ({ initialState, action }) => {
  const [state, setState] = useState(initialState)
  const [data, formAction, isPending] = useActionState(action, initialState)

  // Set the state to the data when the data is available
  useEffect(() => {
    if (!isPending) setState(data)
  }, [isPending])

  const resetState = () => setState(initialState)
  const updateState = newState => setState(prev => ({ ...prev, ...newState }))

  return {
    state,
    formAction,
    isPending,
    resetState,
    updateState,
  }
}

This custom hook allows you to update the state and reset it to the initial value when needed.

#

It's worth noting that useActionState is part of the React 19 RC and Next.js 15, which are still in development. As mentioned in the Next.js upgrade guide (https://nextjs.org/docs/app/building-your-application/upgrading/version-15), useFormState is being replaced by useActionState, but useFormState is still available and recommended until the new versions are stable.

Given the current state of development and the known issues, you might want to consider using useFormState for now or implementing a custom solution like the one suggested above until these issues are resolved in stable releases.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: