@mollycule/redux-hook
v1.0.9
Published
React hook for using redux in your application
Downloads
11
Maintainers
Readme
Table of Contents
About The Project
React Hooks Api has introduced a cleaner and easy way of writing React Components ever. But using Redux in hooks way is not there. Hence, useRedux is a way of using Redux in the hooks way. It's a sort of connect function using hooks api.
Built With
Getting Started
Prerequisites
Following Peer Dependencies are required for using redux-hooks package:
- react: "^16.8.6",
- redux: "^4.0.1"
Installation
npm i @mollycule/redux-hook -S
Usage
- Wrap the root app component with
redux-hook
provider by callingcreateStoreContext<IRootState>
while specifying the shape of Redux App RootState into Generic Parameter.
import { createStoreContext } from "@mollycule/redux-hook";
const { Provider } = createStoreContext<IRootState>();
class App extends Component {
render() {
return (
<Provider store={store}>
<MainComponent />
</Provider>
);
}
}
export default App;
- Now, we can simply use the
useRedux
hook anywhere in our app functional components as
import useRedux from "@mollycule/redux-hook";
import { incrementCount, decrementCount, setIsLoading } from "./actions";
const MyComponent = props => {
const mapStateToProps = state => ({
count: state.count,
isLoading: state.isLoading
});
const mapDispatchToProps = {
incrementCount,
decrementCount,
setIsLoading
};
const mappedProps = useRedux(mapStateToProps, mapDispatchToProps);
const { count, incrementCounter, setIsLoading } = mappedProps;
return (
<p onClick={incrementCount} onMouseOver={() => setIsLoading(true)}>
{count}
</p>
);
};
Note: For mapDispatchToProps
, we can pass a normal function as well that accepts dispatch and returns an object of dispatch bound actions from it as
const mapDispatchToProps = dispatch => ({
authenticateUser: () => {
dispatch({
type: "AUTHENTICATE_USER"
});
},
setIsLoading: (status: boolean) => {
dispatch(setIsLoading(status));
}
});
Passing simply an object of actions, automatically bind them to dispatch using redux bindActionCreators
. Also, you can even skip the second paramter of useRedux hook if you just want to access the props from the store.
Contributing
Contributions are what make the open source community such an amazing place to be learn, inspire, and create. Any contributions you make are greatly appreciated.
- Fork the Project
- Create your Feature Branch (
git checkout -b feature/AmazingFeature
) - Commit your Changes (
git commit -m 'Add some AmazingFeature
) - Push to the Branch (
git push origin feature/AmazingFeature
) - Open a Pull Request
License
Distributed under the MIT License. See LICENSE
for more information.
Contact
Param Singh - @paramsinghvc - [email protected]
Project Link: https://github.com/paramsinghvc/redux-hooks