Skip to content

Instantly share code, notes, and snippets.

@sambostock
Created October 29, 2018 02:26
Show Gist options
  • Save sambostock/a12c88d1dfe92a903cda6d06c0cbf168 to your computer and use it in GitHub Desktop.
Save sambostock/a12c88d1dfe92a903cda6d06c0cbf168 to your computer and use it in GitHub Desktop.
Trivial React State Hook example
import { Component } from 'react'
export default ClassBasedToggle extends React.Component {
constructor(props) {
super(props)
this.state = {
on: false,
}
this.handleToggle = this.handleToggle.bind(this)
}
handleToggle() {
this.setState({ on: !this.state.on })
}
render() {
return <button onClick={handleToggle}>Toggle {this.state.on ? 'off' : 'on'}</button>
}
}
import { useState } from 'react'
export default function HookBasedToggle(props) {
const [on, setOn] = useState(false)
function handleToggle() {
setOn(!on)
}
return <button onClick={handleToggle}>Toggle {on ? 'off' : 'on'}</button>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment