Deconstructing React || Tejas Kumar

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
as Robin so lovingly said my name is Tages as pronounced like contagious I am not contagious I don't have any corona things or anything but I know I know it's that I do work at G 2i g 2i is a company that we have like an army of react engineers and companies come to us and say hey I need five engineers and we're like we know just the people and so we're really kind of matchmaking developers to companies and I lead the team that vets new applying engineers but you know we're not here to talk about that we're not here to talk about me we are here to talk about deconstructing react and before we get into the talk this talk by the way is very technical and we're not even gonna be looking at slides you're gonna be looking at code for the most part but before we get into that I need to clarify why why are we even doing the react works react is good I use react you probably use react everybody who's recommendable wrote a book about react so why and this this very small text is the reason so people have been asking me how do I learn things in case you don't know I am NOT educated I have no degree in computer science I am I didn't even I barely went to school like in a school year I'd attend like maybe nineteen days I'm just completely uneducated but I did take things apart when I was like six seven years old we had a family computer I would break that and my parents would get mad at me but this is how I learned right and so this is kind of what I do with react as well I when I didn't understand rxjs I just took it apart and okay what is this observable thing what is an observer how does it work and similarly with react and so I think there's a lot of value for us if we look under the hood of react a little bit and try to see how it works that we can then take back to our everyday jobs and use for example if I was to ask you right now why are there hooks why are there rules of hooks why can I not put a hook in it if how many of you show me how many of you can tell me the answer confidently yeah there's like four people you're like half okay three people three and a half people examined my hope is after this talk you'll kind of understand these things go back to work and be like ah I can write more fluent react applications okay that's the hope so let's get to work that was literally all the slides except there there's one more I need to give you a disclaimer I I'm not part of the react core team I do not work at Facebook I do not make react I open the pull request once and it was ignored so this is just my playing and experimenting and does not fully represent react if you want that I'd recommend you know Dan Abramov is around not here but you know on the Twitter's look there but for our sake let's get to work and with that I'm gonna exit out a keynote oh I have to accept something okay cool cool cool cool cool cool good alright so let's get to work I'm here in the LAT is this is this sighs good there's a lot of white but we'll see so i'm i will make a folder and i'll call it our react i'm seeing in there typescript is my language of choice you can choose whatever you want but I'd really like typescript and I need something to build it so I'll do parcel two and this is what I needed Wi-Fi I hope the Wi-Fi is good if not I'll like do a dance or something you don't want to see that believe me alright good it's fine you know it feels to me cuz I'm on stage it feels to me like time is moving way faster than it actually is the previous speaker could probably agree okay good it's done so we will open I literally this is I just made this folder so there's nothing here we are starting from zero okay I'm gonna yarn TSC in it so I'm gonna just start up type scripts and so now I have this TS config file up here and I'm just gonna tell it let's make this nice and big I'm gonna tell it we have some JSX and it's react we're using and I'm going to for this purpose turn off all the strictness I don't I don't care don't do this in your apps at work this is exactly but we'll just turn that off for now I will create two files I need an index.html of course that my web server will serve and this will take an indexed ESX so no magic and here I will do indexed ESX so what we're going to look at in this talk three things three react fundamentals and what makes react work number one the virtual Dom okay we've heard this buzzword a lot virtual Dom which will download what is it we're gonna look at that number two we're gonna look at hoax it's the new hotness how do hooks work why do the rules apply and number three concurrent mode which isn't even released but we're gonna kind of look at some specifically one controversial decision that Facebook made and we'll kind of dissect it and talk about it so let's start with the virtual Dom actually we need to start one level even before let's start with JSX so I'm gonna go ahead and serve this app I will do yarn parcel go away yarn parcel index dot HTML and this is gonna start up a little dev server looking Wow one second welcome to 2020 and I'll open this up and we have a blank page whoa all right I'm gonna take this black page put it here and we're gonna be spending a lot of time side by side so I'm loading index tsx let's also open the console get some console action and make that nice and big for you okay so Const a equals div hello you recognize this right this is this is reactor JSX but I have an error reactor is not defined wha I didn't import react from react of course but we're not gonna do that we're gonna make react so I'll just do okay Const react you know what controvert let react that's right and I'm proud of it okay so now react is defined it's an object okay but now react dot create element is not a function so so what we're learning here is this thing calls react not create element okay so okay cool so now I just go ahead and create element expecting it to be a function so I'll just do that okay no errors but also nothing so what does this function what is this thing well here's as far as function expect let's see the arguments that this function expect so I'm gonna look at args here and I will console.log what are you what are you oh look at that there's three arguments to this function div okay so I guess it passes that null and hello and I'm seeing here hello as children so what could the second one be wow you guys are so and girls are so smart welcome to kindergarten react so we will give it a class name BAM okay so we have the second one it's props and so forth I've created an element so what I need to do is I'm just console logging it though so I'm not really creating anything so if I go ahead and let's add some stuff h1 hello person per parens and I will just add some lorem ipsum nothing special great okay just have some text and so I'm calling create element a bunch of times and that's what we see here and this one here we see create element called on the root div that's the only div and there's two undifferenced like some undefined stuff what's going on turns out children's an array so we need to actually return something we're just console logging args now let's return something and console.log that so create element what does it do I'm assuming it creates and returns an element so const element is the future so element is just gonna be an object tag is tag is I'm just gonna change this to actually tag props children children is an array so I'm just gonna do that and so tag props but I want all the props and I also want props children to contain the children okay great and then of course I need to return it but I want to also console.log it return elements BAM great it looks a little bit but we're actually seeing here our first react elements that that have been created I'm not interested in the children I'm interested in the route one the div so what do we got give props class name 2020 children I have two children H one and H one has children and so on so what we're looking at here is a what what's the structure called it's a tree it's a tree what else is a tree the Dom is a tree what we what we have here is the virtual Dom the virtual Dom is just an object is the object with children there's no magic that's what it is and so that's one third of our talk already done it's just here you go let's thank you so we have it's all good but it's in console to the hug man like I'm not even it's all on the screen so next step let's put it on the screen but there's a flaw here because if I make this a little bit smaller what you see is this isn't actually a react component what is this it's a react element it's not a string but nice try it's a it's a react element what do I need to do to make it a component needs to be a function exactly so this now it is a react component and let's follow the convention is called app does it still work though it doesn't I have no console.log because this is a function we need to account for this case so if typeof tag equal equal equal you know what we're breaking all the rules today function I will call it with props okay and that and I need to actually return that sorry I need to what that's right I'll get there good so basically this is what they were saying very good and so it works as expected no problem everything's fine but I need to put on the screen and this is where Part B of react comes in which is the renderer so what we've just done is implement poor-man's react that that's all it is but react is just a part of the puzzle you need to have something that takes your virtual Dom tree puts it somewhere right react native does this for iOS Android whatever react Dom does it for the browser react native Dom does it there's a lot of different there's react ink that does this on the CLI just takes the react tree puts it on there so we need to create our render function so let's just write the API first render that into document dot query selector app already render is not defined of course import rendered no we're writing this so I need to also have an app element here so I'll just do this and here's a here's a protip for you any element in the Dom with an ID the ID is also a global JavaScript variable so you could do that if you really want to yeah but let's let's just let's just be purists about it I might want to get kicked out of this meetup and never come back ever again I don't never happen haha okay so we need to define render so Const render yeah okay we'll do Const and I will take a react element and a container okay and I will render it so what is rendering mean in this case I'm rendering to the Dom so I need to map the virtual Dom element to the actual Dom so I need to document create element so that's what I'll do Const actual Dom element element equals document dot create element react element dot tag because that's what we did up here when we create the element it has a tag property okay so work we're done we next need to take the props apply them on the actual Dom element and we need to take the children nest that all right so if react element dot props if it even has props because it's optional then we'll take the keys of them dot keys react element props we will filter them out for children we'll deal with children separately so P is not too many not children and then for each of them we'll just apply them to our new actual Dom element so we'll say actual Dom element P equals react element P that's pretty much it I need to do the same thing for children so if react element props dulled Rijn what do I want to do for children Randi recursively so I will call for each of the children so react element dot props for each child I will render but this time the react element being rendered is the child into what container this one correct so there we go perfect and then lastly what's the final step append the root to the container so we will container dot append child actual Dom element now this might fail because there's one case we have not yet accounted for but let's see if this works yeah it doesn't it doesn't because cannot read property children of undefined we're not only dealing with objects here if you look at this tree these are not react elements they're just strings do they have children properties they don't they're string primitives and so this thing can be either a react element or a string or a number this is why we need typescript so if this actually that if type if string or number includes type of this thing I need to treat these differently so none of this magic here on a document dot create text node coerce it to a string and put it in there and I want to actually let's move this a little bit that's fine and so what I'll do here is container dot append child and I'll just return I won't do anything else so I don't know what there we go it's working this we have a render we have a render and this this treat can be as deep as I want I could even be like here let's just put an input field in there for fun input type is text placeholder equals name okay cool save that I have input ice holders on I don't know what's happening it's I have a what okay what's the air I mean ah wait wait wait wait line 32 what's my air ah thanks who said that Chum you're in you're the king crowd applauses - good so it's working it's great everything's super but our apps gotten a useless cuz why it has no state it's just like okay great you put stuff on there I could write this in HTML faster than you tages come on you're violating the code of conduct by thinking that kick them out anyway um so state we need state let's add statement that was the virtual Dom that was a renderer let's talk hooks hooks are my jam we need state so let's go here we're changing absolutely nothing except we're just being a little bit more verbose so everything's gonna be fine I don't want these warnings how do I like yes yes yes filter no it's not filter that one no warnings there we go I should also turn off errors and then my app would have nobody okay so cons let's let's do name because I don't like this person it's very impersonal right so Const name set name use state no name by default I guess person why not and we'll go ahead and interpolate here name with a JSX expression and what I want to do is value is name and on change II let's just set name e dot target value now something really interesting you need to notice this is never gonna work why because we're not the actual web platform specification for inputs is this okay it's not this this is react this is web so we're gonna use the platform good let's see what happens oh no you state is not different of course yes then for now we will write it Const use state so let's think about how it works I have my initial state in the argument and then I return what I returned a tuple with the state and a setter simple so initial State and i so i'll just capture the initial state so i actually we're going to mutate that so state initial state and then set state new state state equals initial state kind of ah you can tell i'm on the top of my game today and then we'll return state and set state okay looks okay not bad does it work kind of good good does it update oh no i am such a bad coder okay I quit no just kidding okay so how do we make this work well for one thing we need to re-render right because when you update state rerender so let's take our render function and let's add a rerender function to it so what we'll do is we'll just copy this render and this is poor-man's react okay there's not how they actually do it but let's just do that again what what oh arrow right okay good but let's actually just try that and then we'll call rerender when we call set state so this is not just a reassignment but we will also rerender is this gonna work but why not what's what's wrong state order so now but check this out oh we have a pen child okay so with rerender will clear well clear the first child will clear the root and we add the root whatever and this actually works but what's going on here okay so no that's not true what's what's happening is we can let's use console.log to debug console log okay use state called with initial state and in set state console log set state call with new state all right let's see what's happening you stayed called it person good it mounted change person to Robin it is changing it so we're setting the state but immediately rebounding with the initial state you don't see it so we're starting to understand now how hooks work how do we fix this we use something that is very popular in JavaScript exactly yeah look that that is what closure exactly so if you've ever done a JavaScript interview and somebody has asked you about closure and prototype inheritance this is a prime example react hooks works with closure and closure for those of you if you aren't informed is it's it's when a functions scope encloses over a inside function scope so we're gonna assume that all of this this actually is happening inside a module or a function or a closure every JavaScript module is a closure okay so this file is no exception so we will who said global state you're right but closure state so it's not on window it's inside this module we will have state B this and we what we need here is some type of cursor because we have multiple moving parts of state you know how many times have you seen an app with just one state name right in fact let's add this example so we go to our JSX tree and we'll add two pieces of state okay the count is and this is just a classic example and we'll add some buttons not blur buttons on click and we'll set count to count plus one plus button and count minus one and of course we need to call count set count use state zero alright so this is not gonna do anything because it's the same problem but now we have two moving parts of state cool so we'll have our state in a store in a you versal kind of outside scope was a const States or yeah we can say states equals this and we need something to point to which state am I talking to right now and so we'll just call it let State cursor equals zero so every time we call you state it's going to set a state in this array at index zero at index one at index 2 and so on and these are the moving parts of our app so if you think with me when we call this it's going to set index 0 to person when we call this it's going to set index 1 to our count which is 0 and so forth but we need to work with this so let's yeah we don't need the console logs anymore we will freeze the state cursor here so we'll say Const frozen cursor ah equals state cursor and what we want to do is just only work with that in here this is where closure comes in so we'll say state we don't even need that actually so will reassign States at the frozen cursor okay and we'll return this one from the outer scope good we just need to do one more thing and that is increment the cursor to the next one so when you state finishes it says okay I'm done next piece of state so what we'll do is plus plus exactly that's why it's would let two so state cursor plus plus does this work cannot report what what did I do wrong I miss typescript okay oh so it doesn't like this I think it was cashed parcel has a really nasty cache console.log that's it called it everything oh but I removed these just a second all right so we have this frozen cursor is the state cursor super and we will just return States at we need to sorry we need to also set the initial one frozen cursor equals the initial state perfect and then we will yeah and then we will reassign it here in set state and we will render return that good yeah thanks that's a good that's really important one state cursor plus plus break everything come on okay good it doesn't I think it was just the cash what's go away okay super so now everything's fine does it work it still doesn't work and that's because on render we need to reset the cursor so when we render all the the cursors go to zero we call that state index 0 in the x1 index to everything set and we reset it so let's go back to that rerender here here and we will state cursor is back to 0 this in theory should work but i okay why doesn't so and and this is where I don't know why I tried lets console.log states yeah totally works ah what do you see what's happening we're resetting it I call what again that's right so we need to read the it's not always the initial state good good call so instead of initial state it's either this one if it exists or the initial state perfect and now everything is fine perfect there we go and so from this you can see so if we on every time we mutate state let's just console.log the global state to see what's going on and so you can kind of see them updating here in real time and this is kind of the index that react has the this is a little bit behind because the way input works but this is kind of how it works and so if you have you state called a hundred times you just have an array with a lot of indices but because of this now can you kind of see why the rules of hooks applies what's one of the rules of hooks can't no hooks and conditionals you have to love them unconditionally thanks Ryan Florence so if let's actually just declare these variables here for the sake of demonstration nothing's nothing don't do this in production at all but we let these be things zero and a function that does absolutely nothing and instead of Const we'll just reassign them here and we'll say if I don't know like 5050 math.random greater than point five then we'll set this if not we won't write and watch our app be really weird okay hmm nothing's happening but let me change this and so sometimes it works some and this is because on every render things either this count either works or doesn't so it's just a really confusing our luck is really not yeah so if your app doesn't expect the way you should this is I shouldn't said counted yeah yeah it's just a look at this it's just really strange well where does 380 even come from its octave okay Wow welcome but now it's zero but at some point it's this and so we it's completely unpredictable and this is why we look at this this is why we have the rules Hookes thankfully react will throw ho if you do that so you're good but that should help you understand it alright we're done with two thirds how are we doing on time do we have time to go concurrent or okay cool it's just Lego or whatever awesome awesome alright we're gonna talk concurrent mode and then we will you know eat pizza do whatever we do what a lightning talks like save for those they are amazing cool concurrent mode so for those of you who haven't heard of concurrent mode it is async rendering it's the way react is able to literally suspend it stops rendering waits for some side data to come in from somewhere and then continues the react team came under a lot of fire for the way they implemented it because they people would say they abuse the JavaScript specification by throwing not errors but promises and personally me I don't think that's abusing the language I think it's creatively using the light nor does it say you can't throw whatever you want I could throw the dice in JavaScript if you manage to do that I could do whatever I want so let's look at how that works so let's assume let's go to my function where's my phone well this app app is my component all right and I want to do something asynchronous here Const I'm gonna use the classic example you can put our dog photo URL and how fetch from my favorite API breeds and it's scary that I know that by heart see here lies their response to chase on and then i ieave enou the payload so the payload payload message okay great what do you want now cannot find name payload do do define oh it's a function got it you see how I called it dude all right cool everything's good it's like it's for Oh foreign which means did I get it wrong yes it's five it's I think it's run its image random yeah that's the one wait yeah I always swap them man alright works image random perfect good all right so I'm fetching something but nothing's happening and if I go down here and I try to let's put it here let's do this and see what I see oh look there's nothing oh I have a huge error cannot read probably children if undefined oh my goodness what's happening why did someone tell me why it's a promise it hasn't resolved it says hey I'm gonna go fetch data and come back whatever but not now and we don't if you look here we're not actually doing anything with promises so good luck so we need some way to wrap this promise and know when it's ready and this is the first part of suspense for data fetching in concurrent mode react expose is a primitive called create a resource and it's a function that just wraps your promise it's kind of all it does and the second argument is some type of key a unique key a name so we'll call this dog photo okay now the air is Korean resources we were getting a lot of not defines but we define them so it's all good Const create resource what do I want to do with this it gets to things it gets a promise and the key okay so what I want to do with this is I want to check has this promise been resolved is the data ready to be shown or is it not yet ready and then make a decision so to know if the data is ready or not I need some type of centralized cache again closure not global so Const promise cache cache new and it's just a map nothing special okay and what we'll do is we'll check if promise cache it has our key and we'll just return it promise cache get keep them if it doesn't though what do we do we need something so we need some way from as deep as we are in the tree we need some way to respond to this so we can't just do like one level up as you know with react apps the component trees are deep super deep if you've inspected you would have divot if div div right and so we need something to respond to that from the top now this is how a try-catch works you could throw an error anywhere and catch anywhere and it just knows this emulates a functional programming paradigm called algebraic effects a way to a way to respond to things deep inside globally and so we're gonna use try catch for that to catch something though we need to what I need to do that and we will throw the promise and its cache key and so now let's save this we have an uncaught dog photo the next logical step is to catch it where do we where do we catch it though this is a question you see where we're throwing in the app function where does the app function get called no wrong answer but good try it gets called and create element all the way at the beginning of the talk if you weren't paying attention booooo-whoo now but it get this is where it gets called so we need to try catch this thing so let's try to return that sure but we'll catch the promise cache key and what do we want to do with this we wonder we need to show something the user needs to see something so right off the bat without even thinking I'm going to return let's just do a return a div and props children I am loading and you know what I'll return in h1 because I want to shout it doesn't work it doesn't work why props as no children is what props are children not for each oh it means to be an array typescript I you okay there we go I'm loading we need to wait for loading to finish and then rerender so promised dot ten whenever it finishes data we get data some data we don't know what it is and what we're gonna do is set it in the promise cache dot set key to data and I will re render and so now promise dot then is not a function I might you've been throwing a promise what am i throwing ah yeah you're right you're right I'm not calling it correct correct I need to call it let's go here and promise is thing that returns so I laid me there you're right whoever said that I love you thank you okay good now we have perfect we have the URL but we're not showing it and so just for to close us out let's image this thing alt equals good boy ye and just like that we've implemented concurrent mode it waits thank you and so with that we just implemented poor-man's react and we implemented three pillars on which poor-man's react works let's just quickly talk some takeaways you see because this is this is literally poor-man's react okay it's not it doesn't even come close I mean there's the whole topic of the reconciler bread first algorithm that searches and detects changes and re-renders accordingly we didn't even touch that but that's not the purpose the purpose was to learn and I mean this is a risky move but how many of you learned something new about react oh that's the entire room okay I've done my job good and so let's just quickly talk some takeaways number one building is learning I have so many conversations with people say I should I build this thing I mean I don't nobody uses nobody's gonna use my poor man's react okay I just built it in front of me nobody's gonna use it but I don't care I learned a ton you learned a ton building this together building is there if nobody uses it that's fine it doesn't matter I hope you get your validation from a better place number two time is never wasted I spent a lot of time kind of figuring this stuff out and a lot of people say okay but what you have to show for it well I understand react better but does that really get me richer probably not does it does it help my family and it doesn't but I would still say this time wasn't wasted because I've learned some stuff and so the focus here is learning and lastly this all started when I was just like man am I can I think do I qualify to be an engineer at Facebook do I do I do I think like an Abramov you know what I do I do i am i yeah and so you know and I just it started with wonder how does react actually I've tried to read the react source code I don't get it there's like secret Facebook internals don't use or you'll be fired or whatever like I don't I don't know um but I was wondering and from wonder came this I'd encourage you all so first speaker was wondering about migration how is this working and the wonder led to amazing products and so I'd encourage you with that wake up wander doesn't matter if nobody uses it you're not gonna waste your time is gonna be meaningful with that thank you very very much [Applause]
Info
Channel: Coding Tech
Views: 57,656
Rating: undefined out of 5
Keywords: react, react.js, javascript
Id: f2mMOiCSj5c
Channel Id: undefined
Length: 39min 48sec (2388 seconds)
Published: Mon Mar 02 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.