npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

zustand-create-setter-fn

v1.0.5

Published

A fully type safe utility for Zustand that allows you to easily update state using React style `setState` functions (framework agnostic, doesn't require React).

Readme

🐻 Zustand Create Setter Function 🐻

npm version npm downloads license bundle size install size

A fully type safe utility for Zustand that allows you to easily update state using React style setState functions (framework agnostic, doesn't require React).

🌐 View the demo site

📥 Install

npm i zustand-create-setter-fn

pnpm add zustand-create-setter-fn

yarn add zustand-create-setter-fn

bun add zustand-create-setter-fn

🤔 Why use this?

In short it turns this:

const useCounterStore = create<CounterStore>()((set) => {
   return {
      count: 0,

      // So much boilerplate!
      // You have to repeat this for every setter function in the state.
      setCount: (nextCount: SetStateFnParam<number>) => {
         set((prevState) => ({
            count:
               typeof nextCount === 'function'
                  ? nextCount(prevState.count)
                  : nextCount,
         }))
      },

      // This is cleaner than the above setCount example,
      // though it is still more verbose than using
      // increment: () => setCount(prev => prev + 1)
      increment: () => {
         set((prevState) => ({
            count: prevState.count + 1,
         }))
      },

      reset: () => {
         set(() => ({ count: 0 }))
      },
   }
})

Into this:

const useCounterStore = create<CounterStore>()((set) => {
   const setCount = createSetterFn(set, 'count') // ⬅️ createSetterFn used here

   return {
      count: 0,
      setCount,
      // Pass in a function to use the previous state as part of the new state
      increment: () => setCount((prevCount) => prevCount + 1),
      // Pass in a value directly to set the state to that exact value
      reset: () => setCount(0),
   }
})

Example usage in React

createSetterFn is framework agnostic. It does not need React in order to work. React is a popular framework though and the createSetterFn API is based on the React useState setter function, so I'll use React for this example.

import { create } from 'zustand'
import { createSetterFn, type SetStateFn } from 'zustand-create-setter-fn'

// Set up the type interface (only necessary if using TypeScript)
interface CounterStore {
   count: number
   setCount: SetStateFn<number>
   reset: () => void
   increment: () => void
}

// Set up the Zustand store
const useCounterStore = create<CounterStore>()((set) => {
   const setCount = createSetterFn(set, 'count') // ⬅️ createSetterFn used here

   return {
      count: 0,
      setCount,
      // Pass in a function to use the previous state as part of the new state
      increment: () => setCount((prevCount) => prevCount + 1),
      // Pass in a value directly to set the state to that exact value
      reset: () => setCount(0),
   }
})

// How to use the state inside a component
export function ReactExample() {
   // extract each piece of state from the Zustand store
   const { count, setCount, increment, reset } = useCounterStore()

   return (
      <div className="example-wrapper">
         <label htmlFor="react-input">Count = </label>
         <input
            id="react-input"
            value={count}
            onChange={(e) => {
               const value = parseInt(e.target.value)
               if (isNaN(value)) return
               setCount(value)
            }}
         />
         <div className="button-wrapper">
            <button onClick={increment}>Increment</button>
            <button onClick={reset}>Reset</button>
         </div>
      </div>
   )
}

🚫 Same thing but without using createSetterFn

A demonstration of the amount of additional code needed to achieve the same functionality as the above example without using createSetterFn.

import { create } from 'zustand'

// Setter types need to be manually defined
type SetStateFnParam<T> = T | ((prev: T) => T)
type SetStateFn<T> = (param: SetStateFnParam<T>) => void

interface CounterStore {
   count: number
   setCount: SetStateFn<number>
   increment: () => void
   reset: () => void
}

const useCounterStore = create<CounterStore>()((set) => {
   return {
      count: 0,

      // So much boilerplate!
      // You have to repeat this for every setter function in the state.
      setCount: (nextCount: SetStateFnParam<number>) => {
         set((prevState) => ({
            count:
               typeof nextCount === 'function'
                  ? nextCount(prevState.count)
                  : nextCount,
         }))
      },

      // This is cleaner than the above setCount example,
      // though it is still more verbose than using
      // increment: () => setCount(prev => prev + 1)
      increment: () => {
         set((prevState) => ({
            count: prevState.count + 1,
         }))
      },

      reset: () => {
         set(() => ({ count: 0 }))
      },
   }
})

export function NonSetterFnExample() {
   const { count, setCount, increment, reset } = useCounterStore()

   return (
      <div className="example-wrapper">
         <label htmlFor="react-input">Count = </label>
         <input
            id="react-input"
            value={count}
            onChange={(e) => {
               const value = parseInt(e.target.value)
               if (isNaN(value)) return
               setCount(value)
            }}
         />
         <div className="button-wrapper">
            <button onClick={increment}>Increment</button>
            <button onClick={reset}>Reset</button>
         </div>
      </div>
   )
}

Vanilla TypeScript Example

A demonstration of how this utility can work even with no framework at all. Zustand is doing the majority of the heavy lifting on the state front.

import { createStore } from 'zustand'
import { createSetterFn, type SetStateFn } from 'zustand-create-setter-fn'

interface CounterStore {
   count: number
   setCount: SetStateFn<number>
   increment: () => void
   reset: () => void
}

const vanillaCounterStore = createStore<CounterStore>()((set) => {
   const setCount = createSetterFn(set, 'count') // ⬅️ createSetterFn() used here

   return {
      count: 0,
      setCount,
      // Even though this is vanilla JS, you can use setCount just like a React setState function
      increment: () => setCount((oldCount) => oldCount + 1),
      reset: () => setCount(0),
   }
})

export function initializeVanillaTsExample() {
   const container = document.getElementById('vanilla-ts-example')
   if (!container) {
      return
   }

   container.innerHTML = `
      <label>
         <span>Count =</span>
         <input type="text" />
      </label>
      <div class="button-wrapper">
         <button id="vanilla-ts-increment">Increment</button>
         <button id="vanilla-ts-reset">Reset</button>
      </div>
`

   const inputElem = container.querySelector<HTMLInputElement>('input')
   const incrementButton = container.querySelector<HTMLButtonElement>(
      '#vanilla-ts-increment',
   )
   const resetButton =
      container.querySelector<HTMLButtonElement>('#vanilla-ts-reset')

   if (!inputElem || !incrementButton || !resetButton) {
      return
   }

   const { getState } = vanillaCounterStore
   // updater functions can be retrieved once on initialization from the state like this
   const { increment, reset, setCount } = getState()

   updateInput()

   inputElem.oninput = (e) => {
      const elem = e.target as HTMLInputElement
      const value = parseInt(elem.value)
      if (isNaN(value)) {
         return
      }
      setCount(value)
      updateInput()
   }

   incrementButton.onclick = () => {
      increment()
      updateInput()
   }
   resetButton.onclick = () => {
      reset()
      updateInput()
   }

   /** Vanilla JS is not reactive so we have to update the input manually */
   function updateInput() {
      if (!inputElem) return
      // For state values, `getState()` needs to be called each time they are used
      // This ensures that the value is always in sync with the state
      inputElem.value = getState().count.toString()
   }
}