简体   繁体   中英

Is it a good practice to pass state/custom hook into another custom React hook?

So what I'm asking is...

const useCustomHook = color => {
  const rainbowColors = ["red", "yellow", "blue", "purple"];
  const makeARainbow = rainbowColors.indexOf(color) != -1;
  return { makeARainbow };
}

const Component = () => {
  const [color, setColor] = useState("green");
  const magicobject = useCustomHook(color);
  return <div>{magicobject.makeARainbow ? "Hurray!" : "Nah"}</div>
}

As far as I understand this should be alright so far. See also: https://reactjs.org/docs/hooks-custom.html#tip-pass-information-between-hooks . But what if things get a little more complex and I start to pass a whole hook into another hook?

const useFactory = car => {
  const [availableFrames, setAvailableFrames] = useState([]);
  const [engines, setEngines] = useState([]);
  ...
  const readyForProduction =  availableFrames.indexOf(car.frame) != -1 && engines.map(e => e.type).indexOf(car.engineType) != -1 ...;
  return { readyForProduction, ... }
}

const Component = () => {
  const car = useCarModel();
  const factory = useFactory(car);
  return factory.readyForProduction ? "Hurray!" : "Nah";
}

Both car and factory have their own state(s), handlers, methods, maybe even useEffect s and they can be passed into a presentational component. I haven't found any critique of this so far, so I assume it should be alright, but my intuition tells me that it can lead to some unexpected behaviour (For example, if factory starts to change the state of the car).

There will be no problem because you use your custom hooks in the topmost level, so they are executed every time when the state of the component change.
Just handle the logic in the hooks carefully.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM