helloitsjoe / react-hooks-compose

Decouple Hooks from the presentational components that use them

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Question: Is it possible to pass values to the hooks being composed?

hamlim opened this issue · comments

Based off of the code and examples it seems like there isn't a way to use this HOC while also passing values into the hooks that are being injected into the component.

Example:

Assume useForm needs a defaultValue argument:

import composeHooks from 'react-hooks-compose';

function useForm(defaultValue = '') {
  let [state, setState] = useState(defaultValue);
  return { ... }
}

const FormPresenter = ({ name, onChange, icon }) => (
  <div className="App">
    <div>{icon}</div>
    <h1>Hello, {name}!</h1>
    <input value={name} onChange={onChange} />
  </div>
);

// We could wrap `useForm` in an anonymous function to provide the `defaultValue`
// But what if we wanted to derive the defaultValue from props?
const FormContainer = composeHooks({ useForm })(FormPresenter);

//...

<FormContainer defaultValue="foo" />

Good call, thanks Matt! Seems like composeHooks should optionally accept a function that takes props:

const FormContainer = composeHooks(props => ({
  useForm: useForm(props.defaultValue)
})(FormPresenter);

Updated in v0.4.0, thanks for the suggestion @hamlim !