Redux React Hooks
Redux React Hooks is an experimental library using an experimental version of react (16.7.0-alpha.0).
https://reactjs.org/docs/hooks-intro.html
Why?
To learn, have fun, and provide a solution to a problem that will help other developers.
I won't be able to do this alone, all feedback is helpful!
Current todos and goals
There is still a lot to be done.
- Implement better testing
- Understand the implications of certain patterns
- Work to prove a smooth developing and testing experience
Getting Started
1.) First you will have to install redux-react-hooks, to install all you have to do is run:
npm i redux-react-hooks
To implement, you must be using React >=16.7.0-alpha.0, and redux.
2.) To start using redux-react-hooks, you will still have to wrap the components you want to have access to your store within a "ReduxProvider"
import { ReduxProvider } from 'redux-react-hooks';
import { userReducer } from '../myReducers/userReducer';
const store = createStore(userReducer);
function App() {
return (
{
<ReduxProvider store={store}>
<SomeComponent />
</ReduxProvider>
);
}
3.) Finally, you can begin using your redux react hooks within your components:
import { useReduxState, useReduxActions } from 'redux-react-hooks';
import { createUser } from '../myActions/userActions';
function SomeComponent() {
const { users } = useReduxState(state => ({
users: state.User.users
}));
const actions = useReduxActions({
createUser
});
actions.createUser('Gareth');
...
}
Testing
Before hooks, testing connected components was a pain.
1.) To test a component using redux-react-hooks, you must create a mock store.
Make sure your NODE_ENV=test
import { mockReduxStore } from 'redux-react-hooks';
import renderer from 'react-test-renderer'
import { userReducer } from '../myReducers/userReducer';
describe('SomeComponent', () => {
it('will create user', () => {
const mockStore = mockReduxStore.createStore(createStore(useReducer));
const component = renderer.create(<SomeComponent />);
const usernameInput = component.root.find(el => el.props.id === 'username');
usernameInput.props.onChange({
target: {
value: 'Gareth'
}
});
button.props.onClick();
component.update(<SomeComponent />);
expect(usernameListItem.props.children).toContain("Gareth");
mockStore.teardown();
});
});
In our first example we wrapped in a ReduxProvider, we wont have to do that when testing.
Sandbox
https://codesandbox.io/s/r709zvw47o