I have a React app that manages its global state with useContext and useReducer. My BookListcomponent needs to fetch books from a server when it mounts. If fetching the books was successful they should be stored into global state.
My approach looks as follows
function BookList() {
const [state, dispatch] = useContext(BookContext);
const [loading, setLoading] = useState(true);
useEffect(() => {
BookService
.fetchBooks()
.then(resp => {
setLoading(false);
dispatch({
type: FETCH_BOOKS,
books: resp.data
});
});
}, []);
return (
<div>
{loading
? "Loading ..."
: state.books.map(book => (
<div key={book.id}>{`${book.title} - $${book.price}`}</div>))
}
</div>
);
}
This works but produces the warning
React Hook useEffect has a missing dependency: 'dispatch'. Either ...
Do I have to add dispatch to the dependency array to ged rid of the warning or is there a better way?