Skip to content

Instantly share code, notes, and snippets.

@franky47
Last active May 21, 2019 06:20
Show Gist options
  • Save franky47/14f26d6af6704d6246fe28d77af32506 to your computer and use it in GitHub Desktop.
Save franky47/14f26d6af6704d6246fe28d77af32506 to your computer and use it in GitHub Desktop.
React useDerivedState hook
import React from 'react'
const useDerivedState = <T>(derive: () => T, deps: any[]): T => {
const [value, setValue] = React.useState<T>(derive)
React.useEffect(() => {
setValue(derive())
}, deps)
return value
}
export default useDerivedState
@franky47
Copy link
Author

franky47 commented May 21, 2019

Usage:

import React from 'react'
import useDerivedState from './useDerivedState'

const Demo: React.SFC = () => {
  const [value, setValue] = React.useState('Hello, World!')
  const upper = useDerivedState(() => value.toUpperCase(), [value])

  return (
    <div>
      <input value={value} onChange={e => setValue(e.target.value)} />
      {upper}
    </div>
  )
}

export default Demo

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment