The selected book depends on the URL parameter returned by the useParams
hook. The selected book should also not be redefined from render to render unless the value returned by the useParams hook has changed.
I would like to know if useParams
returns a persistent object from render to render.
const { books, setBooks } = useContext(BooksContext);
const { bookId = 0 } = useParams();
const selectedBook = useMemo(
() => books.find(book => book.id === +bookId) || null,
[books, bookId],
);
2
Answers
The useParams hook in React Router does not necessarily guarantee a persistent object from render to render, as it returns an object containing the URL parameters of the current route.
Here is an example:
your effect depends on
bookId
which is a number it does not depend on the wholeuseParams
object so if it is a differentuseParams
object with the same value ofbookId
thenuseMemo
will not be triggered. also from what I know theuseParams
object does not change value between renders.Here you may don’t need to include
books
in the dependecy array ofuseMemo
there is no need to updateselectedBook
and filter each timebooks
are updated and if you want to track changes for this selected book, becausebooks
may be updated and you want to trackselectedBook
changes so then you can add another value to your context to provide the last updated book Id so when you update a book you change its value as well to the id of this updated book and then you can do something like this: