rehooks
This is still a basic implementation of the redux functionality. It takes advantage of the new features of React hooks to create a global state.
Basic Usage
In your root component, import Provider
from rehooks
and your own reducers with its initialStates:
import React, { useReducer } from 'react';
import { Provider } from 'rehooks';
import YourRootComponent from './otherFile';
import { someReducer, someInitialState } from './reducerPath';
const App = () => {
const reducers = {
myReducer: useReducer(someReducer, someInitialState),
... other reducers ...
};
returm (
<Provider reducers={reducers}>
<YourRootComponent />
</Provider>
);
};
A sample reducer would look like this — you should see this logic very familiar if you have already worked with redux:
export const someInitialState = {
someVariable: true;
};
export const someReducer = (state = someInitialState, action) => {
switch (action.type) {
case 'SWITCH_VARIABLE':
return { ...state, someVariable: !state.someVariable };
default:
return state;
}
};
Then you can use your global state and dispatch with the connect
function, again using the same logic of redux:
import React from 'react';
import { connect } from 'rehooks';
const OtherComponent = ({ someVariable, changeValue }) => {
return (
<div>
<h2>What is the state of my variable?</h2>
<p>{someVariable ? 'True' : 'False'}</p>
<button onClick={changeValue}>Switch</button>
</div>
);
};
export default connect(
(state, ownProps) => ({ someVariable: state.myReducer.someVariable }),
(dispatch, ownProps) => ({ changeValue: dispatch({ type: 'SWITCH_VARIABLE' }) })
)(OtherComponent);