英文:
Are Effect Events really necessary?
问题
在以下官方示例中,我使用普通的JS函数而不是Effect Events,这样更加简洁吗?
Effect Events真的是必要的吗?
这是官方的Event Effect示例链接:
https://codesandbox.io/s/bd0s8d?file=/App.js&utm_medium=sandpack
这是我的修改:
https://codesandbox.io/s/elegant-chaum-cwnyr9
英文:
In the following official example, I use plain JS functions instead of Effect Events, isn't this more concise?
Are Effect Events really necessary?
// official example
function ChatRoom({ roomId, theme }) {
const onConnected = useEffectEvent(() => {
showNotification('Connected!', theme);
});
useEffect(() => {
const connection = createConnection(serverUrl, roomId);
connection.on('connected', () => {
onConnected();
});
connection.connect();
return () => connection.disconnect();
}, [roomId]);
return <h1>Welcome to the {roomId} room!</h1>
}
// My change
function ChatRoom({ roomId, theme }) {
function play() {
showNotification('Connected!', theme);
}
useEffect(() => {
const connection = createConnection(serverUrl, roomId);
connection.on('connected', () => {
play();
});
connection.connect();
return () => connection.disconnect();
}, [roomId]);
return <h1>Welcome to the {roomId} room!</h1>
}
This is the official example of Event Effect:
https://codesandbox.io/s/bd0s8d?file=/App.js&utm_medium=sandpack
This is my change:
https://codesandbox.io/s/elegant-chaum-cwnyr9
答案1
得分: 1
Your change is incorrect, because your function play
is missing in the dependency array of the useEffect
, and every reactive value read by an Effect must be declared as its dependency.
To make it correct, you would need to add play
in the dependencies of the useEffect
, and wrap it in a useCallback
with theme
as dependency. But then it's exactly the same as if you didn't extract showNotification
and put theme
in the dependencies of the useEffect
directly.
This is the purpose of useEffectEvent
: to extract non-reactive logic out of effects, without the need to put it in the dependencies, as explained in the docs.
Please note that it is currently an experimental feature.
英文:
Your change is incorrect, because your function play
is missing in the dependency array of the useEffect
, and every reactive value read by an Effect must be declared as its dependency.
To make it correct, you would need to add play
in the dependencies of the useEffect
, and wrap it in a useCallback
with theme
as dependency. But then it's exactly the same as if you didn't extract showNotification
and put theme
in the dependencies of the useEffect
directly.
This is the purpose of useEffectEvent
: to extract non-reactive logic out of effects, without the need to put it in the dependencies, as explained in the docs.
Please note that it is currently an experimental feature.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论