react-stateful-fn - Functional stateful components
- setState on functional components
- No need to bind your component methods
- Optimized for performance
- Zero dependencies
- Extremely small: < 3kB
Installation
npm install react-stateful-fn# or yarn add react-stateful-fn
Usage
Let's have a look at everyone's favorite sample code: A simple counter widget.
const increase = clicks: stateclicks + 1 const Counter = <div> <div>Clicked stateclicks times</div> <button onClick= >Increase +</button> </div> Counter clicks: 0
As you can see, functional stateful components are good friends with functional setState.
We can do better
But if you care about performance you will probably not be completely happy with the previous example:
The button's onClick
handler is an arrow function defined in the functional component. Thus it will be a different function on every render and will cause the button to re-render every time.
Let's fix that:
const increase = clicks: stateclicks + 1 const Counter = <div> <div>Clicked stateclicks times</div> <button onClick=propsonClick>Increase +</button> </div> Counter clicks: 0
We can wire props and setState together outside the function, similar to Redux' connect()
.
The handlers defined there will be passed to the component as props.
If such a handler returns a function (as seen above) then this function is called with the { setState }
object, so you can update the state according to the event.
Forms
Forms can be quite an elaborate business in React. Fortunately, stateful functional components turn out to be a convenient approach for easy form implementation.
/** * Use as: * * <LoginForm onLogin={(email, password) => { ... }} /> */const LoginForm = <form> <input type='email' placeholder='Email' value=stateemail onChange=propsonEmailChange /> <input type='password' placeholder='Password' value=statepassword onChange=propsonPasswordChange /> <button type='submit' onClick=propsonSubmitClick>Login</button> </form> const initialState = email: '' password: '' LoginForm initialState props
API
stateful(component: Function, initialState: ?Object, propHandlers: ?Object): Function
Make a functional stateless component stateful.
component
This is supposed to be a functional React component. You can use any ordinary functional component. The difference to a stateless component are the additional parameters.
The component will be called with the parameters (props: Object, state: Object, { setState: Function })
.
initialState (optional)
Pass a custom initial state here. Otherwise it will default to {}
.
propHandlers (optional)
Use propHandlers
to pass stateful event handlers as props to the component. Useful to avoid arrow function event handlers which are considered bad practice.
If a property of propHandlers
is not a function it will be added to the component's props as it is.
If a propHandlers
handler returns a function this function will be called with the parameters ({ setState }, props, state)
.
License
MIT