英文:
Returning a function in a React hook giving unexpected result
问题
I'm trying to create a React hook that returns a function that users of the hook will invoke. The hook creates a function inside the hook.
以下是翻译好的部分:
我正在尝试创建一个React钩子,该钩子返回一个函数,使用该钩子的用户将调用该函数。这个钩子在内部创建一个函数。
英文:
I'm trying to create a React hook that returns a function that users of the hook will invoke. The hook creates a function inside the hook.
Here's a minimal example
// fetch.js
import { useEffect, useState} from "react";
export const useFetch = () => {
const [fn, setFn] = useState(null);
useEffect(() => {
const fn_ = () => console.log("test")
setFn(fn_)
}, []);
return fn;
}
// App.js
import { useFetch } from './fetch';
function App() {
const fn = useFetch()
return (
<div className="App">
hello
</div>
);
}
I have the Strict mode disabled as well.
// index.js
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<App />
);
Even though I'm not invoking fn()
, I see it getting executed and console log output.
Any idea why this is happening? Pretty sure I'm doing something wrong but can't figure out what.
Edit:
Thanks for the answer below. Found this explained in React FAQ https://react.dev/reference/react/useState#im-trying-to-set-state-to-a-function-but-it-gets-called-instead
答案1
得分: 2
问题在于将函数传递给状态设置器,它假设您正在使用功能性更新。
如我在上面的注释中所说,效果钩子和状态是完全多余的,尤其不应该用于函数。
export const useFetch = () => () => console.log("[useFetch] test");
英文:
The problem with passing a function to a state setter is it assumes you're using a functional update.
Like I said in the comments above, the effect hook and state are totally redundant and you should especially not use it for a function
export const useFetch = () => () => console.log("[useFetch] test");
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论