Allow value to be a function so we have the same API as useState

Viewed 16

I started analyzing useLocalStorage hook from https://usehooks-ts.com/ and I am wondering why they are actually allowing value to be a function in setValue ? There is a comment "Allow value to be a function so we have the same API as useState" but I don't really understand it. In what case value would be a function? Could anyone explain it for me?

 try {
      // Allow value to be a function so we have the same API as useState
      const newValue = value instanceof Function ? value(storedValue) : value

      // Save to local storage
      window.localStorage.setItem(key, JSON.stringify(newValue))

      // Save state
      setStoredValue(newValue)
1 Answers

This is a "functional update":

If the new state is computed using the previous state, you can pass a function to setState. The function will receive the previous value, and return an updated value.

It is especially interesting if you update the state value asynchronously, while the current value may have changed in the meantime, and your final update must account for this new change.

Related