Hey your friends. So I get this question of fair amount and so I thought I'd try to answer it and podcast form and the question is why don't why is it not a good idea to set a ref during your render function? So there are exceptions to this and understanding the reasoning will help you understand what those exceptions are.
But basically, if you read my blog post on the Epic React dot dev slash articles, there's a blog post about the latest ref pattern and in that I put a use layout effect and,There with ref dot current equals some callback or whatever And a lot of people ask me why do you need to put that in a use effect?
Why can't you just put that? You know you're calling it every render anyway so you may as well just put it directly in the render function. So the reason that you don't want to do this is it actually is mostly just for future proofing. So right now that will technically work and it and it there shouldn't be any problem with it, but when eventually if the reacting does finally release concurrent mode as an official feature of React,Then you could wind up in a problem and that problem would be very difficult to reproduce and very difficult to debug.
So in general, this is why the react team is just been so adamant about your render methods being item potent, which basically means that it can be called as many times as it reacts once to and the same thing will occur regardless of how many times this function is called.
That's like an oversimplification of what that means but anyway, so imagine a scenario with a concurrent mode where reacted.The rendering your reactor and then a high priority event happens as it's going through rendering and so it says okay never mind, let's stop rendering will deal with this high priority event and then we'll come back and we'll re-render stuff and so if you set it during the render function, you may actually be setting it to a value that is never actually used and so potentially if you end up using that you're using a value that was created for a render that was never actually committed to the DOM.
It's hard to describe the bugs that you.Could have there but hopefully you understand why that could be a problem. And and so it because there's no real issue with putting something inside of a user factor used layout effect and that's really the only time where you can run code and be certain that the render was actually committed to the DOM then you may as well just put it there and make sure that you keep your render functions side effect free.
So, hopefully that kind of made sense is interesting and useful. I hope you have a fabulous day andTake care.