0

I want to create a higher order function which contains useReducer hook as a singleton in order to composite with other components. But i got an error:

Error: Invalid hook call. Hooks can only be called inside of the body of a function component.

My HOF:

const initialState = {
  status: ''
};

const reducer = (state = initialState, action) => {
  switch(action.type) {
    case 'SHOW':
      return {
        ...state
      }
    default:
      return state;
  }
}

const WithReducer = WrappedComponent => (props) => {
  const [state, dispatch] = useReducer(reducer, initialState)
  return (
    <>
      <WrappedComponent {...props}/>
    </>
  )
}

export default WithReducer;

And a try to compose:

connect(mapStateToProps, mapDispatchToProps)(WithReducer(App));

Where did i go wrong ?

  • May I ask you why you a trying to wrap a component into an HOC rather than directly using the `useReducer` hook inside the component that needs it? – secan Oct 16 '20 at 09:10
  • The main idea was that we can connect to redux state through connect function without a need to drill props, and i was thinking about repeating that functionality by creating a HOF with a useReducer HOC and connect different parts of my app through a composition. But my mistake was that useReducer creates a new instance of a state and by composing components with my custom HOF i won't have a singleton state but rather independent instances. I thin i should use towards context and useReducer). – Олег Войтинський Oct 16 '20 at 09:35

1 Answers1

2

got an answer to myself

 const WithReducer = WrappedComponent => {
      const Reducer = (props) => {
        const [state, dispatch] = useReducer(reducer, initialState);
        return (
          <>
            <div>{state.status}</div>
            <WrappedComponent {...props} state={state} dispatch={dispatch}/>
          </>
        )
      }
      return Reducer;
    }