I have a React Component like shown bellow (some parts are ommited) and I'm using redux for state management. The getRecentSheets action contains an AJAX request and dispatches the response to redux which updates state.sheets.recentSheets with the response's data.
All this works as expected, but on building it throws warning about useEffect has a missing dependency: 'getRecentSheets'. But if I add getRecentSheets to useEffect's dependency array it starts to rerun indefinitely and thus freezes the app.
I've read React documentation about the useEffect hook https://reactjs.org/docs/hooks-faq.html#is-it-safe-to-omit-functions-from-the-list-of-dependencies but it doesn't provide a good example for such usecase. I suppose it is something with useCallback or react-redux useDispatch, but without examples I'm not sure how to implement it.
Can someone please tell me what the most concise and idiomatic way to use redux action in useEffect would be and how to avoid warnings about missing dependencies?
import React, { useEffect, useState } from 'react'; import { connect } from 'react-redux'; import SheetList from '../components/sheets/SheetList'; import { getRecentSheets } from '../store/actions/sheetsActions'; const mapStateToProps = (state) => { return { recentSheets: state.sheets.recentSheets, } } const mapDispatchToProps = (dispatch) => { return { getRecentSheets: () => dispatch(getRecentSheets()), } } const Home = (props) => { const {recentSheets, getRecentSheets} = props; useEffect(() => { getRecentSheets(); }, []) return <SheetList sheets={ recentSheets } /> }; export default connect(mapStateToProps, mapDispatchToProps) (Home);
connect. You just have oneuseDispatchand as manyuseSelectorsas you need. And I believe thatuseDispatchwill not return a new function everytime making it effect dependency safe.