Answer the question
In order to leave comments, you need to log in
How to use useStore, useSelector, useDispatch hook?
New hooks have been released with Redux version 7.1.0. I don't understand how to use these hooks in practice. Can someone give an example of using these hooks?
Answer the question
In order to leave comments, you need to log in
1. useDispatch - getting the store.dispatch function in the component. Previously, to call an action, a functional component had to be wrapped in a connect call:
const Foo = ({ dispatch }) => {
const handler = useCallback(() => {
dispatch(action());
}, []);
return (
<Bar onClick={handler} />
);
};
export default connect()(Foo);
const Foo = () => {
const dispatch = useDispatch();
const handler = useCallback(() => {
dispatch(action());
}, []);
return (
<Bar onClick={handler} />
);
};
export default Foo;
const Foo = ({ value }) => {
return (
<Bar value={value} />
);
};
const mapStateToProps = state => ({
value: state.value,
});
export default connect(mapStateToProps)(Foo);
const Foo = () => {
const value = useSelector(state => state.value);
return (
<Bar value={value} />
);
};
export default Foo;
const valueSelector = state => state.value;
const Foo = () => {
const { dispatch, getState, subscribe } = useStore();
const value = valueSelector(getState());
useEffect(() => subscribe(console.log), []);
const handler = useCallback(() => {
dispatch(action());
}, []);
return (
<Bar onClick={handler} value={value} />
);
};
export default Foo;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question