I'm trying to create a simple component to dispatch an action using the React Redux hook useDispatch
- and I'm getting an error. I've trimmed the component down to where the error occurs. It happens when the useDispatch function is called.
import { useDispatch } from 'react-redux'
const MyComp = () => {
useDispatch()
return null
}
export default MyComp
This is the error I'm seeing in dev console:
Uncaught TypeError: Object(...) is not a function
at MyComp (MyComp.js?cc4c:4)
at renderWithHooks (react-dom.development.js?d018:12938)
at mountIndeterminateComponent (react-dom.development.js?d018:15020)
at beginWork (react-dom.development.js?d018:15625)
at performUnitOfWork (react-dom.development.js?d018:19312)
at workLoop (react-dom.development.js?d018:19352)
at HTMLUnknownElement.callCallback (react-dom.development.js?d018:149)
at Object.invokeGuardedCallbackDev (react-dom.development.js?d018:199)
at invokeGuardedCallback (react-dom.development.js?d018:256)
at replayUnitOfWork (react-dom.development.js?d018:18578)
I've trimmed this down further so there are no parents in the react tree.
const store = configureStore()
ReactDOM.render(
<Provider store={store}>
<MyComp />
</Provider>,
document.getElementById('root')
)
Module Versions
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-redux": "^7.1.0",
UseSelector and useDispatch in React Redux useSelector and useDispatch are a set of hooks to use as alternatives to the existing connect() higher-order component. The equivalent of map state to props is useSelector. It takes in a function argument that returns the part of the state that you want.
useDispatch() This hook returns a reference to the dispatch function from the Redux store. You may use it to dispatch actions as needed.
Error: could not find react-redux context value; please ensure the component is wrapped in a <Provider> If you need to access redux store in App component, you should wrap the App component with <Provider /> , so that it can provide the react-redux context values to App and other nested components.
The useSelector creates a new object so the return value always changes. The sixth example fixes this by changing the equality function which useSelector uses for memoization. In this case the return values are compared by using shallow equality which prevents extra renders.
In my case, I was doing:
import { useDispatch } from 'react'
instead of:
import { useDispatch } from 'react-redux'
🤦♂️
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With