Reputation: 1199
In my react/redux app, i'm using dispatch to call the action that retrieve data from state in redux each time the component is mounted. The problem is happening on useState My way does not work
Below is the error I'm getting:
React Hook useEffect has a missing dependency: 'dispatch'. Either include it or remove the dependency array. Outer scope values like 'getInvoiceData' aren't valid dependencies because mutating them doesn't re-render the component react-hooks/exhaustive-deps
Here is my code:
const TableSection = () => {
const invoiceData = useSelector((state => state.tables.invoiceData));
const dispatch = useDispatch()
useEffect(() => {
dispatch(getInvoiceData());
}, [getInvoiceData]);
(...)
export default TableSection;
Upvotes: 1
Views: 4571
Reputation: 29312
This is not an error, its just a warning.
You can fix this by adding dispatch
in the dependency array.
useEffect(() => {
dispatch(getInvoiceData());
}, [dispatch]);
second part of the warning message states, Outer scope values like 'getInvoiceData' aren't valid dependencies because mutating them doesn't re-render the component react-hooks/exhaustive-deps, you also need to remove getInvoiceData
function from the dependency array of useEffect
hook.
Anything from the scope of the functional component, that participates in react's data flow, that you use inside the callback function of useEffect
should be added in the dependency array of the useEffect
hook.
Although, in your case, it is safe to omit dispatch
function from the dependency array because its guaranteed to never change but still it won't do any harm if you add it as a dependency.
Upvotes: 3
Reputation: 53934
You need to add dispatch
function to dep array:
const TableSection = () => {
const dispatch = useDispatch()
useEffect(() => {
dispatch(getInvoiceData());
}, [dispatch]);
Its safe to add it to dep array because its identity is stable across renders, see docs.
Note: like in React's useReducer, the returned dispatch function identity is stable and won't change on re-renders (unless you change the store being passed to the , which would be extremely unusual).
Upvotes: 5