Skip to content

Instantly share code, notes, and snippets.

@andywer
Last active July 15, 2017 11:41
Show Gist options
  • Save andywer/7d4766a18eb10b36d6208bded7cf302a to your computer and use it in GitHub Desktop.
Save andywer/7d4766a18eb10b36d6208bded7cf302a to your computer and use it in GitHub Desktop.
React Stateful (!) Functional Components
// counter.js
import stateful from 'new-fancy-statefulness'
const Counter = (props, state, { setState }) => (
<div>
<div>Clicked {state.clicks} times</div>
<button onClick={props.onClick}>Increase +</button>
</div>
)
const increase = () => state => ({ clicks: state.clicks + 1 })
export default stateful(Counter, { clicks: 0 }, {
onClick: event => ({ setState }) => setState(increase())
})
@andywer
Copy link
Author

andywer commented May 15, 2017

There was a small mistake in the first version. Instead of correcting onClick={setState(increase())} to onClick={() => setState(increase())} I eliminated the arrow function by adding a props.onClick handler.

That should make it faster if the component gets re-rendered frequently :)

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