Skip to content

Instantly share code, notes, and snippets.

@andrewluetgers
Created October 16, 2020 18:40
Show Gist options
  • Save andrewluetgers/67259f4a3ac41aed2a1701d1a3a2fc4c to your computer and use it in GitHub Desktop.
Save andrewluetgers/67259f4a3ac41aed2a1701d1a3a2fc4c to your computer and use it in GitHub Desktop.
Works like useState but for Class Components using this.setState
function useThisState(key, component, initialState) {
let set = (val) => component.setState({[key]: val}),
initial = !(key in component.state)
if (initial) {
set(initialState)
}
let retVal = initial ? initialState : component.state[key]
return [retVal, set]
}
// e.g. (from within a react class component)
// let [open, setOpen] = useThisState('open', this, false)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment