Skip to content

The missing React Hook to handle form initial values that depend on dynamic data from SWR, React Query, and more

Notifications You must be signed in to change notification settings

javascripter/react-hooks-use-form-state

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

10 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

useFormState()

🎉 A simple and concise React Hook to handle form initial values that depend on dynamic data from SWR, React Query, and more.


🚧 The Problem

When using data fetching libraries like useSWR() and useQuery(), Managing the initial state of a form state based on dynamic data using useState() can be challenging. If the fetched data is stale on the initial render, the form state may not update correctly after revalidation. Simple state synchronization via useEffect() may result in unintended loss of edits due to race conditions.

✅ The Solution

useFormState() automatically handles updates to the initial value until the user starts editing the value.

import { useFormState } from 'react-hooks-use-form-state'

const { data: product } = useSWR(`/products/${id}`)
const [name, setName] = useFormState(product?.name ?? '')

// 1. `name` variable will update itself whenever product name changes.
// 2. After `setName` is called, `name` will not react to initial value changes, preventing any loss of changes made manually.

✨ Features

  • 🔄 Automatically updates the initial value until the user starts editing
  • 💻 Supports TypeScript
  • 🛠️ Functional state updater pattern
  • 🔄 Provides a reset function to revert to the initial state
import { useFormState } from 'react-hooks-use-form-state'

const [state, setState, resetState] = useFormState(dynamicData)
setState((prevState) => nextState)

// For example, you can clear state on modal open
const onModalOpen = () => {
  resetState()
}

📦 Installation

yarn add react-hooks-use-form-state

or

npm install react-hooks-use-form-state

🔍 How It Works

The simplified version of the hook looks like this:

function useFormState(initialValue) {
  const [isChanged, setIsChanged] = useState(false)
  const [state, setState] = useState(undefined)

  return [
    isChanged ? state : initialValue,
    (state) => {
      setIsChanged(true)
      setState(state)
    },
  ]
}

In addition to the above, useFormState() supports TypeScript, functional state updater pattern, and a reset function to revert back to the initial state. useFormState() also provides stable setState and resetState similar to React's setState() hook.

📚 Related discussions

About

The missing React Hook to handle form initial values that depend on dynamic data from SWR, React Query, and more

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published