Back to the video

Confident web development with React by Julien Phalip

Transcript

By Speaker 1, Speaker 2, Speaker 3, Speaker 4. From DjangoCon US 2015. Published September 24, 2015.

Watch the video Markdown version 6,432 words · auto-generated · en

Summary

Flux gives React applications a predictable unidirectional data flow: actions reach stores, stores provide state to views, and state changes trigger rendering. Julien Phalip shows how Django can provide a REST API while React renders the client interface, including initial data loading through Ajax or serialized data embedded in the HTML, optimistic updates, and server-side rendering with the same React components. He also covers JavaScript asset tooling, testing rendered React components from Django, and argues that React complements rather than replaces Django: it is most useful for complex, dynamic parts of a site.

Transcript

Automatically transcribed, so expect mistakes in names and technical terms. Filler words are removed.

0:16 Introduction

Hi

Speaker 1

everyone, can you hear me? Okay, yeah. So thank you for coming today to my talk. Just very briefly about me. So I worked with Django since 2007. I've been a Django Core commuter since 2011. And if you're ever interested in what I'm saying, you can always check out my Twitter account. I work on Neuron. We are a web agency based in San Francisco and have offices all around the world. And I encourage you to check out our website if you'd like to see what we are up to. So about this talk. So this talk is about Django and React. And while it does assume that you know a little bit about React, I'm still going to cover some of the basic principles of flux and React. And then I'll show some examples of how Django and React can work together.

1:03 Flux Architecture

Speaker 1

So first about flux. So flux is an architecture whose core principle is based on unidirectional data flow. Now that core principle is not particularly novel or groundbreaking. It's been used for a long time in many disciplines like video games, for example. And you may also argue that it's been used in the web in general with traditional websites. If you consider the traditional HTTP request, server-side template rendering response cycle over and over. But it is a little it is a bit new in the world of rich client-side web application. So let's see how it all works. Typically it starts with an action. An action

is basically an event that is triggered by various things. It could be triggered by a user clicking on something on the user interface It could be also regular event that is triggered at a regular interval by a timer. It could also be data being pushed via WebSockets from a server. So whenever an action is triggered, that action is called by a dispatcher, which would then pass that action along to a store. A store is just responsible for holding the state of your application. So whenever the store may modify the state and the internal data and then pass that data over to the views and then the view is responsible for rendering itself It may also have subviews. So in that case it will pass along that data down to its

subviews and then the subviews will run on themselves and so on. So what's very important in this architecture is that whenever something changes, needs to change in the state of your application, what you want to do is to trigger a new action. So for example, if a user will click somewhere on an interface, then you will trigger an action, a new action. And then that action would be called by the dispatcher. And then you will enter this whole cycle again. You will then go through this entire cycle of re-rendering the entire in the entire interface. React itself is really just about this view system. It just f folk focuses purely on rendering. Everything that sits outside. Well there are several implementations available out there. I can cite for example

Redux, Reflux, Flammox, Flexor, and I don't know, Alt, Malty. There's about a couple dozens extra It's still pretty new. There are no clear winners at this point. So it really comes down to personal preference and to the nature of your application. Hopefully within the next few months there will be one or two that emerge as de facto standards. But for now, I just encourage you to try it a few and see what which one feels the best. So let's see now what some of the advantages of flux are. So first of all, it streamlines the rendering process. As we just saw, anytime that anything happens that would that might impact the state of your application, you enter the

same entire rendering process. Which means that you will approach the rendering of your page initially the first time the same way as on the second time, the third time, etc. And because of that, it means that your cognitive load is drastically reduced. Because you don't really need to worry about how the different views impact each other as the state of your application changes. You can really focus on one particular view at a time That then makes for a simpler code base because you don't have to deal with mutations for your views, that eliminates a whole class of potential bugs that you basically never have to worry about.

4:57 Benefits of Flux and React

Speaker 1

And that is very liberating. So all of that put together really makes for consistent, predictable behaviors, and that goes a long way in making you as a developer more confident about your application. Now let's see some advantages of React specifically. So React abstracts the DOM with components. It allows you to think of the architecture of your application really in terms of modules and submodules. And again, you can always focus on one piece at a time. It also handles all of the DOM mutations automatically. Mutating the DOM is something that can be quite complex sometimes, especially in to do in an efficient way, well React will handle all that for you. And it is also agnostic about the rest of the stack

The only thing that React really cares about is that you feed it some data and then we'll take care of all the rendering. It really doesn't matter in which context React is used, it could be used to render your entire application, but it can also be used to just render one little piece of an existing website. For example. And it also doesn't matter where the data came from, why the data changed, how it was changed, which means that you can use it with pretty much any backend. And obviously in our case, we'll be using Django. So to illustrate some of those concepts, I'm going to walk you through a small demo app that I've built. It's very simple. It's just a list of photos. You may filter those photos based on whether it's black and white or color. And you can also then select some of those photos to mark them as your favorites

6:31 Django and React Architecture

Speaker 1

But first let's see what are the pieces involved. So first we have Django, which will be responsible for providing a REST API that allows you to access and manipulate the data server-side. And then we'll have React that will be responsible for rendering the UI client side and to handle all the user interactions. Now let's see how those pieces fit together. So first we have the client, so that in this case it will be the browser. React will be rendering the page, and then whenever the user will click on the photos. A POST request will be emitted to the server, to the API, and then Django will update the database. We then serialize the current state of the data and then pass it over to

back to the client. And then React will be able to re-render the page to reflect the changes that have been made And we try and follow this unidirectional flow of data. Now you may be wondering, okay, so how does React do to render the page initially, how does it have access to the data to hydrate the stores, meaning to load the stores with initial data? I'm going to cover a couple different methods. One that you might think of as conventional is when the server will first return a pretty much empty document, HTML document, and then we'll do another Ajax request just to fetch the data so we can then render the content on that page. Another

Method which I might think of less conventional is when the server, so in this case Django, will serialize the data and stick that data into the initial HTML document. and pass it as a global javascript variable. And that is for example how Instagram does it. So now let's take a look at a working demo. Okay, so can you all see? Make it a bit Bigger. Right. So here we have our application. We have all our over our photos to the left. You may filter

the photos and whether they're black and white or color. You can also represent the same list in two different ways. You can represent it here as a list or as a as a grid of thumbnails. And whenever you click on a photo, you will see that first it will highlight the photo and it will also update the panel to the right which just lists all of the favorites that have been selected. So what's important to what I want to emphasize here is whenever I click on an event, or sorry, on a photo, whenever I click on any of those buttons, the entire page gets refreshed. You can really see it because React is really fast

9:34 API and Initial Rendering

Speaker 1

at doing that, but any event here triggers a full page refresh. And you can see also here that whenever I click a photo. it sends requests to the to the server, so post request, delete request. All right, so now let's see how what the code looks like. I'm going to start with the models So it's really simple stuff here. We can you all see?

Yeah, I'll make it a bit bigger. So we only have two models here, a photo which will hold just all of the photos. Each photo has a URL, also has a Boolean flag that will indicate whether it's a color or black and white and then another model the favorite model which will hold basically all of the pointers to the photos that have been favorited Then the API. The API here was built with a Django REST framework. If you're familiar with Django REST framework, it should all look pretty standard. The only thing that I'm doing here that is A little bit different is for the favorite endpoint when I add or remove a favorite.

So for example, when I add a favorite, so that's the create method here, I will first do the actual action of adding the favorite to the database. But then I will also serialize all of the current favorites and send that back with the response. And this is just a small optimization here that I'm doing, and I'll I'll just explain why I'm doing this. And you can see here that I'm doing the same for the destroy method, which is called when you delete or remove a favorite Okay, so then let's take a look at the view. The view is extremely simple. It's this one at the top, Ajax hydration. All it does really

11:51 React Components and Declarative UI

Speaker 1

is that it will run all this template and it's basically empty. There's nothing in there, we just have the links to our JavaScript. And here I've just added a header. And as you can see here, initially we basically have absolutely nothing. nothing. So we do need to do that second Ajax request to load the data. So that is done with this function here. So this function gets called as you first display the page, that empty page in the browser. So first we will render our React main view.

So this render method here is going to get called. So the very first time that that this is going to get called, the store is it won't be hydrated, it will there won't be any data at this point. So we will first display this progress bar. So this is what you can see here when I refresh the page. Okay. Then here I'm I'm just waiting for a second, it's just to simulate a slow connection to the internet. But really what this what this does is that it wouldn't call this method fetch data.

Fetch data really all it does is it just runs a couple of It just calls to we so we call our API, fetch that data, and once we receive all of it, then we are ready to hydrate the store. So we basically load that data into our store. At that point Our view is automatically going to be re-rendered. So this render method is going to get called again. And at that point we still we are still displaying the progress bar. The progress bar is still displayed on the page. But at that point the store has been hydrated, so we are going to render this instead. Which is the album component, that's a custom component that I've made.

And React will be smart enough to know that it needs to remove the progress bar and instead dump our album component. And by the way, you can see here that I'm using progress bar that's just A pre-made component that I've taken from the React Bootstrap library, which is a React implementation of Bootstrap, but it kind of shows how you can build your application a bit like Lego pieces So now let's drill down into our album our album component. Again, very simple here. All that we do is to add

two subcomponents. The photo panel, which is basically the grid of photos to the left, and the favorite panel, which is the small panel to the right that displays all of the favorites. that have been selected by the user. In each case we also pass down some data. So the photo panel needs to know about the photos, so it can render the photos and also the favorites so it knows how to highlight the different photos. That have been favorited and whereas the favorite panel only needs to know about the favorites. So here you can see that we're passing down data to the sub-views. Let's take a look at the photo panel. That's probably the most complex. Again, this random method is going to get called automatically at this point. First thing that we do here is to just filter the dataset that we have

based on those I'm not sure what 's looking so big here because of the resolution Yeah, okay, looks better at this. Okay, so it's going to look for whatever is selected here to filter down and be to know exactly what photos we need to display. And that's just a custom method here, just a little bit of JavaScript that's going to go through the list and only return the photos that you we actually want to display. Alright, so now that we have the list of the photos to display, we then render some more components, some more subcomponents.

Here I'm going to call this function here Render Photos. It's just a custom method that I have in here. here in this class, in this components class. All I do here is to loop through all the photos. I com I do a little bit of computation. and I try and find out for example if the photo the current photo is favorited so I can figure out what color if I need to display any highlighting around it. So that's the style here. And then based on what we've selected between the thumbnails here or the list option, we are going to take two different paths. So in this case, if we are if we have decided that we wanted a show as a thumbnail, then we're gonna render this

this particular photo as a thumbnail. That's another component that I've picked. from the React Bootstrap library. And then we assign the URL, et cetera, and the given style. Or if at this point I have selected this piece, then this function is going to get called and I run I'm going to render it as a list group item component. Again you can see here that there's absolutely no code that says remove the thumbnail, add the list items instead or vice versa. All I have to say is I can code the this component in a very declarative way. I can only focus on a given state and say this is how you should display it given this state or you display it this way

given this state. All of the transitions here are basically handled by React because it's going to go through that method every time. And you can see here that I I'm passing an action. to both methods here. So whether I click on photo here or a list item here, the same action is going to be triggered. It's called toggle favorite. Now you can see what is going to catch that action and deal with it. So it's this method here. First, we try and figure out whether the current photo that's been clicked is a favorite. If it is, then we are going to remove it from our favorites. If it's not, then we are going to add it.

19:05 Optimistic Updates

Speaker 1

So let's take a look for the ball adding. And now here I'm going to do two things. And really the this first thing is not particularly React specific, it's more of an optimization for the user experience. I do not want to wait for the round trip to the server to be able to display feedback to the user that the that photo has been favorited so what I'm doing here is that I'm holding a local data structure which is basically an array that holds all of the current favorites. And I will add that photo to that local data structure. And then I will call this method here propagate state, which is going to trigger a full render of the entire page, which is going to cause the photo you just clicked to already be

highlighted. And this is because and this is called an optimistic update. Is when you trust that the backend is most likely going to work and you just don't want to let the user wait for too long before they see anything change on the interface. And then this is when we actually change the actual data server side. So for that we need to run a post request to our API and I will pass down the photo. Then what I do here, and again this is this piece is optional. If you remember earlier I said that whenever I run an API call, I always return the current state of the data server side, because this is really the authoritative data. This is the data

I really trust, the one that is staying on the server. I return that from the server so then I can replace my local data structure with the data that was provided from the server. And here I'm only doing this just to give myself some extra confidence that the UI reflects the actual state of the data server-side. If everything went well really nothing is going to change, but React is going to be smart enough to figure that out. Because here I replace the data that came back from the server, I replace it with into the local store and then propagate the state. So that's going to trigger another full render. However, React is going to be smart enough to know that, okay, well, I had already made that chance previously.

I was I had already highlighted that photo. And I see that you're asking me to highlight that photo again, so I'm not gonna do anything. So this is not this is going to have very low impact on the performance. And this catch method here is if something ever went wrong on the server, then I'm going to fetch the data again from the server, and then that is also going to retrigger a full render and that's going to allow me to roll back. Previously I had optimistically updated the interface, but if something went wrong on the server, that's going to basically revert that change. And I do the same thing when I want to remove a server here, a favorite here. I first optimistically remove that.

22:08 Serialized Hydration

Speaker 1

that favorite from my local, my local storage, and then pro trigger full render, and then same thing I send a request to the server. and same thing again I replace the local data with the new the server the data I came back from the server and re-render everything So that was for the Ajax hydration that I mentioned earlier. There is another technique for the purely the initial rendering, and that is This one. So this is exactly the same demo. It looks and you know works exactly the same. The only thing that changes here

is that we are going to be calling This view serialized hydration. So what we do here, we first serialize the data using the serializers from my API, the same ones I then dump it all of that stuff into a JSON object and I pass that over to my template. And here we just dump that JSON object into the HTML inside a global variable. So this is here what you can see if I show the source you can see that's the object.

So What's what's good about this, what's interesting about this is that it saves you from doing an extra Ajax call. So it means that along with the initial HTML document, you will already have the data, you'll be able to right away start rendering things. Now you may you want to be cautious if you have a gigantic amount of data that might not be suitable because it's gonna make the initial call to the server slower. So you need to you need to find out what method works best for you, either the Ajax hydration or the that pre-serialized method. Okay, so that was for a brief demo. There 's something else I wanted to talk about, which is Server-side rendering.

24:29 Server-Side Rendering

Speaker 1

So server-side rendering may be interesting in different cases. First of all, if you're concerned about SEO, Obviously it would be much more easier for search engines to crawl your site and to index the content of your site if All of that good stuff, all that content was pre-rendered as part of the HTML document. Doing server-side rendering also is also good for if your audience has a large amount of mobile devices that it's also good because it will save some resource and CPU processing on your on your device because that would save them the effort of rendering

the page initially inside the browser. And it's also good because since the page comes pre-rendered, you can already start consuming it. You don't have to wait a little time for it to render. And React make that actually pretty easy to do. The cool thing about it is that again I mentioned earlier React really doesn't care in which context it's being used. It means that you can actually use the exact same code to render things. on the server as you would and as I shown earlier in the browser. And that is called universal JavaScript. Universal just stands for the fact that it's the actual same code that you use. That is sometimes also referred as isomorphic. JavaScript.

And it's actually easy to implement if you use the right tools. I recommend using Python React. It's a small nifty Python application that will allow you to do server-side rendering. with any Python frameworks and it does come with Django support. You will also need to use a very simple node HDP server to do this. So let's see how all those species fit together. So first in the client, so that's our browser, when the user will first type in the URL to access your website So there will be a get a get request sent to the server. Django will then fetch the data, serialize it as JSON, and send that over via HTTP to that separate node

server. That's that node server, all that it does is just to render HTML. It will use the data that you provided and then use the React component, so those JavaScript React components to render whatever component you want And then it will return some HTML. Django will put all that together and send it over to the client. And past that point, any subsequent refresh that needs to happen. Will be done by React client side, exactly the same way as I showed earlier. And the cool thing is that it will use exactly the same code, the same React components that I showed earlier. So let's take a look at a quick demo. So it is this function, this URL here.

Again, exactly the same, exactly the same thing. Works and behaves the same. It's the exact same code, basically. Now let's see what happens server-side. So here, this is the view, the Jago view that it's going to get called. Here again, I first serialize the data using the same serializers from my API. We then call this small function. That's a function that's provided by Python React. All that you need to pass to that function is the reference to the component that you want to render and then the data that you you've just serialized. So in the background that function is going to call that separate node server is going to send all that data to

that server via HTTP. That node server is also very simple. It's basically just a dozen line of code. It will receive the data. Passed from Django via HTTP that contains both specification of which component to render and then with which data. And then call that React render function, which is going to use our same our same component that I was showing earlier. And then you will it will result into some HTML, which we are going to return back to Django. So this is where we are now. Now we have all of our rendered HTML and we are ready to pass it down to our Django template.

29:09 Asset Pipelines

Speaker 1

And here we basically just output that HTML into our template. And you can see here that we have all of the HTML that has been pre-rendered And past that point, the exact same React component take it over from there and the same the same happens. It's exactly the same thing. Okay? There's another couple topics I wanted to cover. First about asset pipelines. I personally recommend using something like Webpack, Gulp, and browser or

gulp and browserify for bundling all of your javascript code. Up until about a year ago I was using pretty heavily Django pipelines and Django compressor to do that sort of stuff. But the tooling in the JavaScript world has improved a lot in the past year. And now I think it's a bit more flexible to use those JavaScript tools to handle that stuff. And also front end developers are already used to using those tools and they feel much more comfortable using those as opposed to more opaque tools like Django pipelines or Django components I also recommend using Babel for the JSX transpiling. JSX is that template-ish syntax that was showing in

The code samples earlier that r React uses and Babbel we just transform that into actual JavaScript that your browser can execute. And then finally, when comes the time comes to push code to production, then I recommend using Django static files. The app and also the manifest tidy file storage which will apply a unique hash to each of your assets which will guarantee that all the caches in your browser in the CDNs etc. will be busted and your users will be using the very latest version of your asset. And finally we also wanted to talk a bit about testing A good test suite should contain some unit test, and for that you could use some JavaScript frameworks like Jasmine, Mocha, Gest

31:29 Testing React Components

Speaker 1

QUnit. Also, I recommend doing some functional testing for that. You can use something like Selenium and Django Dascom with some support for that, in particular with the LiveServer test case. If you're interested in all that stuff, you should stick around because there's going to be a talk right after this that's going to cover some of those topics. But I also wanted to cover one particular method, which is sort of a hybrid between unit and integration testing. And that is actually using the same tools as I was describing earlier about server-side rendering. Even if you don't really care about server-side rendering, you could use the same tools to do some amount of testing. I'm going to show you how that works.

So here we have a very simple test case method. In the setup here, I just create a bunch a bunch of photos. Photo one, two, and three, and I'm going to create some favorites. So just marking photo two and three as favorites. So then in the test method I first serialized the favorite data again using the same serializer from my API. We then call the same render component method from Python React. So what this is going to do is going to render our favorite panel component. by passing that favorite data over to the node server that's running in the background. And then render that component.

Again, here we're talking about this one to the to the right. And just and just that component in this case. So then you basically retrieve all of the HTML that that's been rendered for that component, and then you can basically test the content of that HTML. You could test, for example, which of the photos are present inside that HTML. So here I check that photo one, since it's not a favorite, I check that it's not in the HTML, and I check that photo two and three actually are. You may also use something like a tool called PyQuery. It's a pretty nifty Python library which sort of mimics the API from jQuery, except in Python.

That allows you to select pieces of your HTML. So in this case I'm I'm selecting the div that has the batch class. So it's this thing here. And I just check that its text is two, since we only have two favorites in this case. And you may also use a method that comes with the Django test team framework. A cert HTML equal where you can compare two blocks of HTML. So here I'm I'm inspecting the HTML from the H4 tag and that's this whole thing here so favorites and the badge And I'm checking that it actually is exactly that HTML. Now I don't recommend using this for huge amounts of HTML, but if you

are strategic about it, it can be pretty powerful. Because essentially we're here we're using Python and Django to test JavaScript because the background this is actual JavaScript that's been used to render that HTML. And that's about it for my talk. So thanks again for coming. I've published all the code if you are interested in checking that out. And I also published my slide. Later and I'm happy to try and answer some of your questions. Thank you.

35:15 Questions

Speaker 2

Hi, great talk. Hi, thank you.

Speaker 1

Thanks.

Speaker 2

I'm curious if you've explored good ways to integrate this with Django Forms at all.

Speaker 1

Django Forms. Yeah.

Speaker 2

Forms, form sets. Or if this is geared more towards, you know, application style or native style web Page rendering.

Speaker 1

Right. So I assume you're talking about validating the data. I don't know. I have not. I don't see why you wouldn't. Some but I guess so at the end of the day, if you if you're going to use React to render your forms, you do want to use React component. So you cannot use just the output that the Django forms would give you. But there might be a way of turning that into instead of rendering raw HTML, you could configure your forms to instead render React components. You could take that route. Otherwise you could just use the

You could still use the forms validating process but just hand over all the runnering to react

Speaker 2

I guess the reason I bring it up is I've I like the convenience of Django forms, right? You can just set it all up and then render with as p or anything like that. But then I've found it difficult to construct native style apps. And so, you know, generally I would I would gravitate more towards this method if that's what I were trying to So I was just curious about you know what your experience was with that.

Speaker 1

Yeah, so again I have not used Django Fonts with this, but I believe you would have to sort of re-implement the outputting of HTML from the Django Forms So and actually that would be a cool project actually. That'd be awesome if somebody wanted to take that on. And that's something I'll definitely look into. It's interesting.

Speaker 2

Thank you.

Speaker 1

Thanks

Speaker 3

Hey there. So I've been using React lately kind of similarly to how you're you presented it here. here. It's been really useful and it's been very fun, but the one thing that still makes me very uncomfortable is JSX.

Speaker 1

Oh yeah.

Speaker 3

And it also makes the front-end developers that I work with very uncomfortable because they're used to working. in something like handlebars, for example. And so embedding, I mean even having things like if you're specifying a class on a DOM component, it use class name, you know, the camel caste. attribute instead.

Speaker 1

Yeah.

Speaker 3

Is there any compelling reason to use JSX over trying to use one of the alternatives?

Speaker 1

Really, I think it comes down to personal preference. I personally actually really like it. And I know that the community is pretty divided about it. Some love it, some hate it. I just advise you just go with whatever works best for you. There's something you might be interested in looking into is React templates. It's a library that it's basically an interface in between. So it will you will be able to write templates that kind of look like Angular templates But will output JavaScript. So it's basically a replacement for JSX. So you might bot you might want to look into that. It will definitely look a lot more familiar and you'll be able to use the regular

HTML-ish or attributes and tags.

Speaker 3

Do you think there's any downside to doing that or is it really just personal? preference?

Speaker 1

No downside that I can think of. At the end of the day it's just it's basically just JavaScript. What I like about it is that it gives you a bit more power than you would have. With templates typically because you have the all the power of JavaScript constructs and data structures and you know processing that you can use to your advantage to do cool things for looping through list and you know doing some kind of computation. So I personally like that but I do understand that it's a bit an off-putting for or you know if you're really if you feel more comfortable with just HTML like syntax. Thank you.

Speaker 4

Okay, so my question is with a Django. You sort of you're showing here that looks like Django effectively is being reduced to Django Rest framework, purely serving the API portions of what's going on and maybe some really light templating to put up the initial page that then React is doing all of the actual hard work. Yeah. Is this a question where Django's place in the world is just changing, or is there room for Django to interact better with these parts, or is there some intersection conglomerate that of the two that we can use, preferably one that means I don't have to write JavaScript for a living.

Speaker 1

No, I don't think so at all. So what I think is great with React is that it's great for doing really complex dynamic sites that you know when you have lots of things that change all over the place But that's not all websites. Not all websites are like that. And so some websites are a bit more static and Django is perfect for those. You know the traditional Django, not just the API side of Django. But you can then still use React to focus on the small bits of your site that may be a little bit more dynamic. So I just see React as a complement to you as a Django developer, totally not as a replacement for Django. at all. It has to be used.

React really shines when you have things that change that are dynamic, but that doesn't mean that all websites need that. Or if they do, it sometimes it's just a small portion of the site and you can it both cases you can use React.

Speaker 3

Thank you, Julianne.