javascript – In React, s it really bad to call a potentially asynchronous function directly in render code?
I have a question regarding best practices in React.js.
Recently, I came across a blogpost that claimed you shouldn’t directly invoke a callback in React render code. And while intuitively I would agree to that statement (and I have never invoked a callback directly in render code before), I started questioning this statement and am wondering why (and if) that is really the case).
In other words, my question is: Why should I not do something like in the following? What would break if I did?
export const MyComponent = ({callback}) => {
callback(); // <-- Why not?
return Irrelevant text here
;
}
Note that callback could be an asynchronous function returning a promise (or not).
Some further thoughts:
- The react documentation itself provides an example where a state setter is called directly in render code – so maybe it’s not so bad after all…
- Note that I do not want to make the components render function asynchronous. In other words: I am not doing
await callback();, I am doingvoid callback(); - Since there might be suggestions to wrap the execution of
callbackintouseEffect: Sure, I could. But the question is rather: Do I have to? And why do I have to? I agree thatuseEffectis made for use cases like when I want to trigger something which happens as a side effect of the current component rendering (e.g. when you want to send a tracking event when you render the page for the first time) or also when I want to access/manipulate the DOM after rendering. Why would I also have to use it when I simply want to trigger something that should happen a tick after the render method has been executed? - Note that the execution of
callback()might in reality be wrapped in an if-statement or so so that it does not execute on every render.
Read more here: Source link
