Is there any way to use useReducer or any equivalent thing in React native class Components?
Yeah reducer method is raw js function. Can we use it in class directly rather joining it with states of class?
function init(initialCount) {
return {count: initialCount};
}
function reducer(state, action) {
switch (action.type) {
case 'increment':
return {count: state.count + 1};
case 'decrement':
return {count: state.count - 1};
case 'reset':
return init(action.payload);
default:
throw new Error();
}
}
class App extends React.Component {
...
render() {
return(...)
}
}
Create a wrapper component that uses the
useReducerhook and pass thestateanddispatchfunction as props.Example:
This might be better abstracted into a reusable Higher Order Component though.
Example:
...
Consuming in class component: