Show notes
https://epicreact.dev/the-latest-ref-pattern-in-react
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 isit not a good idea to set a ref during your render function? So there areexceptions to this and understanding the reasoning will help you understandwhat 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 Iput a use layout effect and,There with ref dot current equals some callbackor whatever And a lot of people ask me why do you need to put that in a useeffect?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 thereason that you don't want to do this is it actually is mostly just forfuture proofing. So right now that will technically work and it and itthere shouldn't be any problem with it, but when eventually if the reactingdoes finally release concurrent mode as an official feature of React,Thenyou could wind up in a problem and that problem would be very difficult toreproduce 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 becalled as many times as it reacts once to and the same thing will occurregardless 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 reactorand then a high priority event happens as it's going through rendering andso it says okay never mind, let's stop rendering will deal with this highpriority event and then we'll come back and we'll re-render stuff and so ifyou set it during the render function, you may actually be setting it to avalue that is never actually used and so potentially if you end up usingthat you're using a value that was created for a render that was neveractually 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 noreal issue with putting something inside of a user factor used layouteffect and that's really the only time where you can run code and becertain that the render was actually committed to the DOM then you may aswell just put it there and make sure that you keep your render functionsside effect free.So, hopefully that kind of made sense is interesting and useful. I hope you
have a fabulous day andTake care.
