I want to get the data from the store not on component render but only on button click (or other event).
Imagine the situation where there is BooksList component that renders multiple BookItem components. A single BookItem component has a button which fires handleExportClick as presented below:
const BookItem = ({ book }) => {
const highlights = useSelector((state) =>
state.highlights.filter(q => q[1].book === book.title)
)
const handleExportClick = () => {
bookExport(highlights)
}
return (
<Button onClick={handleExportClick}>Export</Button>
)
This solution works but it has a major flaw. The highlights variable is calculated for every component (every BookItem). This is not optimal, because the data is required only when user clicks Export button.
I tried solving this problem by moving useSelector inside handleExportClick but this doesn't work.
const BookItem = ({ book }) => {
const handleExportClick = () => {
const highlights = useSelector((state) =>
state.highlights.filter(q => q[1].book === book.title)
)
bookExport(highlights)
}
return (
<Button onClick={handleExportClick}>Export</Button>
)
}
This gives
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
- You might have mismatching versions of React and the renderer (such as React DOM)
- You might be breaking the Rules of Hooks
- You might have more than one copy of React in the same app See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
Which is understandable.
What's the current pattern for getting the data from the store but only on demand?
Solution
Use useStore hook for directly accessing store.
import { useStore } from 'react-redux'
const BookItem = ({ book }) => {
const store = useStore()
const handleExportClick = () => {
const highlights = store.getSate().highlights.filter(q => q[1].book === book.title)
bookExport(highlights)
}
return (
<Button onClick={handleExportClick}>Export</Button>
)
}