useEvent
[ ru ]since
useEvent
introduced in effector-react 20.9.0
Bind event to current scope to use in dom event handlers.
Only effector-react/scope
version works this way, useEvent
of effector-react
is no-op and does not require Provider
with scope.
Note
Useful only if you have server-side rendering or writing tests for React-components.
useEvent(unit)
Arguments
Returns
(Function): Function to pass to event handlers. Will trigger a given unit in current scope
Example
import ReactDOM from "react-dom";
import { createEvent, createStore, fork } from "effector";
import { useStore, useEvent, Provider } from "effector-react/scope";
const inc = createEvent();
const $count = createStore(0).on(inc, (x) => x + 1);
const App = () => {
const count = useStore($count);
const incFn = useEvent(inc);
return (
<>
<p>Count: {count}</p>
<button onClick={() => incFn()}>increment</button>
</>
);
};
const scope = fork();
ReactDOM.render(
<Provider value={scope}>
<App />
</Provider>,
document.getElementById("root"),
);
useEvent(shape)
Arguments
shape
Object or array of (Event or Effect): Events or effects as values which will be bound to the currentscope
Returns
(Object or Array): List of functions with the same names or keys as argument to pass to event handlers. Will trigger a given unit in current scope
Example
import ReactDOM from "react-dom";
import { createStore, createEvent, fork } from "effector";
import { useStore, useEvent, Provider } from "effector-react/scope";
const inc = createEvent();
const dec = createEvent();
const $count = createStore(0)
.on(inc, (x) => x + 1)
.on(dec, (x) => x - 1);
const App = () => {
const count = useStore($count);
const handler = useEvent({ inc, dec });
// or
const [a, b] = useEvent([inc, dec]);
return (
<>
<p>Count: {count}</p>
<button onClick={() => handler.inc()}>increment</button>
<button onClick={() => handler.dec()}>decrement</button>
</>
);
};
const scope = fork();
ReactDOM.render(
<Provider value={scope}>
<App />
</Provider>,
document.getElementById("root"),
);