[英]Am I using React hooks wrong?
I wanted to create a sevice-like hook that doesn't hold state, it just exports an object with funtions.我想创建一个不包含 state 的类似服务的挂钩,它只是导出一个带有函数的 object。
I first started with this:我首先从这个开始:
export default useFoo = () => ({ // some functions here... });
But then I realized that this wouldn't be the best approach because a new object is going to be created every time the hook is called and I don't want that - I need one global object with the same reference across all components, so then I tried this:但后来我意识到这不是最好的方法,因为每次调用挂钩时都会创建一个新的 object 而我不希望这样 - 我需要一个全局 object 在所有组件中具有相同的引用,所以然后我试了这个:
const foo = { // some functions here... };
export default useFoo = () => foo;
It works as expected, but I'm not sure if it's the right way to do it.它按预期工作,但我不确定这是否是正确的方法。 Is there a better way to achieve this?有没有更好的方法来实现这一目标? Or should I use context maybe?或者我应该使用上下文吗?
EDIT: I know that I can just export a plain JS object and not bother myself with hooks, but I need it to be a hook because I use other hooks inside.编辑:我知道我可以导出一个普通的 JS object 而不是用钩子打扰自己,但我需要它是一个钩子,因为我在里面使用了其他钩子。
It works as expected, but I'm not sure if it's the right way to do it.它按预期工作,但我不确定这是否是正确的方法。 Is there a better way to achieve this?有没有更好的方法来实现这一目标?
If foo never changes, and doesn't need to close over any values from the other hooks you're calling in useFoo
, then that's fine.如果 foo 永远不会改变,并且不需要关闭您在useFoo
中调用的其他挂钩的任何值,那很好。 If it does need to change based on other values, then you can use useCallback
and/or useMemo
to only recreate the object when relevant things change.如果它确实需要根据其他值进行更改,那么您可以使用useCallback
和/或useMemo
仅在相关内容更改时重新创建 object。
export default useFoo = () => {
const something = useSomeHook();
const foo = useMemo(() => {
return { /* some functions that use `something` */ }
}, [something]);
return foo;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.