5

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(...)
  }
}
CrackerKSR
  • 1,380
  • 1
  • 11
  • 29

1 Answers1

5

Create a wrapper component that uses the useReducer hook and pass the state and dispatch function as props.

Example:

const Wrapper = props => {
  const [state, dispatch] = useReducer(reducer, initialCount, init);

  return <App {...props} {...{ state, dispatch }} />;
};

This might be better abstracted into a reusable Higher Order Component though.

Example:

const withUseReducer = (...useReducerArgs) => Component => props => {
  const [state, dispatch] = useReducer(...useReducerArgs);

  return <Component {...props} {...{ state, dispatch }} />;
};

...

export default withUseReducer(reducer, initialCount, init)(App);

Consuming in class component:

class App extends React.Component {

  ...

  render() {
    const { state, dispatch } = this.props;

    ...

    return(...)
  }
}
Drew Reese
  • 165,259
  • 14
  • 153
  • 181