3
votes

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?

1
Basicly yes, but the reference to this function won't change so it's optional actually. - gadi tzkhori

1 Answers

2
votes

The warning is not very relevant here since the doc suggests omitting dispatch from the list of dependencies of useEffect and useReducer, but you can safely put it in the dependency array because the identity of the dispatch function of useReducer is always stable.

the doc says:

React guarantees that dispatch function identity is stable and won’t change on re-renders.
This is why it’s safe to omit from the useEffect or useCallback dependency list.