A babel macro that helps you reduce the React boilerplate.
$ npm install reactive.macro --save
babel-plugin-macros is required before using this package.
If you are using create-react-app, it has included babel-plugin-macros.
import React from 'react';
import { state, bind } from 'reactive.macro';
export default () => {
let a = state(1);
let b = state(2);
return (
<div>
<input type="number" value={bind(a)} />
<button onClick={b => b += 1} >b+</button>
<p>{a} + {b} = {a + b}</p>
</div>
);
};
See live demo.
Equals:
import React, { useState, useCallback } from 'react';
export default () => {
const [a, setA] = useState(1);
const [b, setB] = useState(2);
return (
<div>
<input type="number" value={a} onChange={useCallback(e => setA(e.target.value), [])} />
<button onClick={b => setB(b + 1)} >b+</button>
<p>{a} + {b} = {a + b}</p>
</div>
);
};
Declare a state.
initialState
- Initial value.
In component:
const App = () => {
let count = state(0);
return <button onClick={() => count + 1}>Clicked {count} {count > 1 ? 'times' : 'time'}</button>
}
In custom hook:
const useToggle = () => {
let visible = state(false);
const toggle = () => {
visible = !visible
}
return [visible, toggle];
}
You can update the value of count
directly without calling setState
.
Note: using array methods like push
and splice
won't trigger re-render. Instead you can use spread syntax.
let users = state([]);
const addUser = (user) => {
users = [...users, user];
}
Bind a state to a form control.
state
- The state which is declared bystate
macro.
const App = () => {
let name = state('');
return (
<div>
<input value={bind(name)} />
Hello {name}!
</div>
);
}