dispatch in react redux code example
Example 1: using redux with hooks
import React from "react";
import { useDispatch, useSelector } from "react-redux";
import { addCount } from "./store/counter/actions";
export const Count = () => {
const count = useSelector(state => state.counter.count);
const dispatch = useDispatch();
return (
<main>
<div>Count: {count}</div>
<button onClick={() => dispatch(addCount())}>Add to count</button>
</main>
);
};
Example 2: what is dispatch in redux
function dispatch(action) {
if (typeof action !== 'object' || obj === null) {
throw new Error('actions must be plain object.');
}
if (typeof action.type === 'undefined') {
throw new Error('Actions may not have an undefined "type" property.');
}
reducer(currentState, action);
}