Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Beyond JavaScript: Exploring .NET Blazor’s Challenge to React

Sign upSign InSign upSign InSascha KlompFollowITNEXT--ListenShareAs a frontend technology, my team was still using Razor, a .NET library to create server-side web pages. Sadly, the speed at which Razor renders its pages and sends them to the client, does not have the performance that is desired nowadays; instead of this archaic server-side request/response model, web pages built in modern frontend frameworks use a more client-side approach for updating content on the page. To select a more modern frontend technology, we compared .NET Blazor, the descendant of Razor Pages, with the popular JavaScript framework React to determine which one would be a better fit for our team. Let’s understand these technologies a little better so a good comparison can be made..NET Blazor is an open-source web development framework which was created by Microsoft in 2018. This framework is used for building interactive client-side web UIs using .NET and C#. It can be considered a descendant of Razor pages, which was previously used with an MVC approach for full stack .NET development.Blazor has been made with modern web development in mind, supporting a couple of different scenarios:Blazor is supported by the most popular modern browsers.The main promise of Blazor is to be able to build full stack web apps without writing a line of JavaScript.In addition, it promises the following things:In its essence, all Blazor apps are component based. This means that elements within the UI are separated into smaller reusable components, such as a modal, form, or table.These components are written in Razor markup, which was already used for Razor pages back in the day. This syntax makes switching between C# and HTML markup possible on the fly. Blazor is not relying on the old-school request and response model, but instead adopts techniques from modern JavaScript UI frameworks by only using components for client-side design and logic implementations.The Blazor components can be reused both in- and outside of their assemblies: within the same project, they can be nested and reused or used in other projects as class libraries or NuGet packages.Even when using the Blazor server-rendering option, Blazor will not send a complete web page over the line every time an action gets triggered. Instead, it will compare its own version of the DOM with the browser’s DOM, distil a difference/diff from it and only sent back this smaller subset through SignalR. This prevents the site from feeling sluggish and slow by having to do a partial/full page reload on every user interaction.A similar technique is used for Blazor WebAssembly (WASM). To recap very briefly, what WASM is: a binary instruction format that can run in a stack-based virtual machine. Essentially, all four modern browsers (Chrome, Firefox, Edge, and Safari) have such a virtual machine integrated into the browser that allows for the compilation of programming languages other than JavaScript. You could compare this a little bit to how Docker works, and it provides you with a memory-safe environment where you can run modules in. This WASM sandbox allows Blazor to access the JavaScript context from within itself, which Blazor uses to construct its own copy of the DOM, does a diff comparison, and corrects the browser DOM accordingly if any changes pop up.Blazor could be an excellent technology for our team because they are already comfortable working with C# and .NET as technologies. Blazor is relatively similar in approach to Razor Pages, although it introduces some new concepts that we would have to familiarize with. It is a relatively mature technology and contains some documentation and community help.React is a full stack JavaScript framework, which is based on Vanilla JavaScript. It was first released by Facebook (now Meta) in 2013 as a free, open-source library. The core of React is very bare bones; it does not by default contain functionalities like routing and data fetching, instead it gives you the flexibility to create your own or implement a third-party solution for them.By using other libraries, it is possible to run React:React promises a component-based system that allows for easy designing and fast loading. It allows the possibility of building full stack applications in React using additional frameworks such as Next.js or Remix.Aside from that it promises:React applications are component based, which means that, just like Blazor, an application consists of smaller components (like a button or form) that can be reusable.Describing these components happens in a special markup language called JSX (JavaScript Syntax Extension), which allows to seemingly mix HTML with React logic. React allows you to manage state for your components. This can be done by hosting your state locally within a component, or in a more complex scenario, through using a global state store like context. This state will be managed by React and it will associate it with the correct node within the UI tree it corresponds to.The way React responds to state changes within a component is to re-render the component and all its descendants. It does this to keep a consistent and up-to-date state of the UI. This UI state is kept in a virtual DOM, a lightweight version of the actual DOM. In addition, React keeps another virtual DOM and uses them both to continuously compare when new changes come in. The result of this difference will be used to update the real DOM. This process makes updating the DOM faster, since the virtual DOMs only contain a blueprint of the DOM tree, but they are never rendered, which saves a lot of time and resources. React calls this technique “Reconciliation”. If you are curious and want to learn more about React’s rendering strategy, check this excellent article.React could be a good fit for the team, because they are already comfortable with using some JavaScript for frontend development. It is the most popular frontend framework and a more popular technology compared to Blazor. The technology is very mature (>10 years old) and has a lot of documentation and community help available.Based on information and experiences with these technologies, we also wanted to get a good practical feel of working with these two technologies, so we ran an experiment of creating two Proof of Concept projects for the same type of application; one in React, the other in Blazor WASM. We divided our development team into equal groups and spent around 20 working days developing the applications.To make a good comparison, we set some common restrictions and requirements. For example, both parties were required to build an application to annotate and watch videos. Specific functionality was listed as required, and as restrictions, we kept the application client-side only.Both teams reported having a pleasant experience getting more used to the technologies. All members of team Blazor could program in C#/.NET already and found the learning curve relatively low. On the other hand, they experienced the more intricate systems like working with the shadow DOM and the changed application lifecycle as a lot more challenging to get comfortable with.On the other hand, the React team was also comfortable with using JavaScript and found the framework very intuitive with a low learning curve. The more complex state techniques like using global stores, were more complex to master.Let’s compare the benefits and disadvantages of both technologies based on our hands-on experiences building the PoCs:Both Blazor and React support the use of components, which makes the application very modular. It provides a lot of abstractions that allow developers to put more focus on the actual design and less on the implementation details. For example, see the React component below that contains all video controls for a specific video:Within a separate screen component, this can be abstracted by importing a component and passing the required parameters. This is especially useful for rendering the same component multiple times with different input:For Blazor this process is similar, where after creating a component it can be used like below:In addition, Blazor also supports data binding and attributes to ease development. This is especially useful for validating forms. By annotating the model with attributes as shown below:By using the bind-Value attribute, it is possible to set the value of the model property when an onchange DOM event is fired. It is also possible to change the event it fires on by using the @bind:event attribute. Doing proper validation like this is also possible in React, but requires installing additional third-party libraries or writing your own custom solution.Both Blazor and React utilize a component lifecycle that is responsible for initially rendering a component, dealing with subsequent re-renders based on state changes and finally destroying the component when the component is no longer needed. In Blazor’s case, this is significantly different from Razor Pages’ lifecycle, and when using it without the appropriate knowledge, it can cause side effects and other problems. Especially when interfacing with JavaScript interop, the Blazor team ran into DOM synchronization issues.Similar challenges are true for React. Whether using the more modern React Hooks or lifecycle methods in a class based component, when used without understanding the component lifecycle, either can cause infinite re-renders, race conditions and other unwanted side effects. For the React team, especially managing state within React hooks posed quite a steep learning curve to the junior in our team. For example, issues would surface when attempts were made to use a state variable together with the method to update itself in one useEffect hook, a very common anti-pattern:When it comes to component lifecycles, it is important to fully understand its intricacies prior to getting started with either technology. Especially when the team is new to this concept, it might take a bit of effort to fully grasp these concepts.Both React and Blazor provide ready-made templates to a certain extent. For Blazor development, when using Visual Studio, it is possible to follow a wizard to get a completely scaffolded template:These options also include using authentication based on individual accounts, or Microsoft Identity Platform. Using connected services within Visual Studio, it is possible to immediately create and set up an Application Registration, which allows for the entire application to work out of the box, including authentication through Azure. Additionally, it is possible to create your own custom Visual Studio template for Blazor. The Blazor team used a standard template including authentication and Progressive Web App (PWA) support to bootstrap their application.React on the other hand, provides templates (from [email protected] up) through running npx create-react-app my-app-name --template cra-template-. The React team supplies two basic templates, one for JavaScript and one for TypeScript. The community provides templates with the cra-template- prefix on NPM. It is also possible to build a custom template by following the Create React App tutorial. The downside of this method is that depending on the additional libraries used in your application, it might be hard to find a good open source template online, which might force the team to dedicate extra time into writing their own custom template. The React team chose to do the latter, and created a custom template based on the community template for React TypeScript with PWA support.In order to measure the performance of the initial load, Lighthouse performance analyses were used on both pages:As can be seen, the initial loading time of Blazor is a lot slower compared to React. This is because, on the initial loading of the web page, large dll files have to be downloaded to the client in order to execute in WebAssembly. On subsequent visits, however, these files will be cached locally and the performance will be a lot faster, likely reaching similar speeds to React’s loading times. For production builds, Microsoft has additional best practices available to improve performance.React’s initial paint is really fast compared to Blazor, mainly by using efficient bundling and tree-shaking, the files that are pushed to clients are relatively small, which makes the first load quite fast.Note: it should be mentioned that neither projects heavily focused on optimizing performance in production builds, since they are simple PoCs.Blazor could be considered slightly more secure than JavaScript. Since Blazor is mostly running its processes in WASM, it executes in a memory-safe environment. WASM has been designed to only allow applications to execute in standalone sandbox environments and can only communicate to the outside through its intended APIs. When WASM runs on a browser, its data flow is also restricted through the same-origin policy. Thanks to this, it is more difficult to tamper with the code that is executing within the WASM sandbox. However, this does not mean that WASM is 100% safe, there are still vulnerabilities to consider, such as side-channel attacks or some vulnerabilities based on race conditions. The DLLs that are sent to the client from the Blazor server are harder to decompile compared to JavaScript code. In addition, there are third-party obfuscation tools available to make decompiling DLLs even more difficult, such as Babel Obfuscator. It should be noted that obfuscation alone is not a good security measure.A JavaScript frontend’s files are by definition considered insecure, since all the files are pushed to the client and are accessible without having to decompile the files. To show an example, when using environment variables for more sensitive values, they will always be hardcoded into the code:So, as stated above, both client-side frameworks are insecure by nature. However, since Blazor runs in WASM and applies more obfuscation, it can be considered slightly more secure.Note: When it comes to frontend applications, you should always consider them insecure, regardless of the technology used. This is because all the files required for them to run will be pushed to clients, consequently exposing any secrets or other sensitive information they contain. In addition, the processes that happen on the client side can be tampered with. It is always important to take this into consideration when deciding which functionalities of your application will live in the frontend. Ideally, it should be only logic that is responsible for handling the user interface (UI). Any information sent for processing to a backend server, should always first be validated and authentication and authorization should always be done in the backend or by a dedicated identity service like Microsoft Identity Framework.Since Blazor is a Microsoft product, there is a guarantee for continuity and investment into growing the community. Although it might take a bit more time, a lot of effort is being made to further mature the development community surrounding this technology. That said, when running into more specific problems, it was very difficult for the Blazor team to find answers online.For React, the technology has been around for over 10 years and is used by many Fortune 500 companies. In addition, React keeps scoring incredibly high on developer satisfaction and community use in large scale surveys like the State of JS. This aligns with the experience of the React team, who could find a plethora of answers for every problem they ran into, no matter the complexity.Not all NuGet libraries support Blazor. In our experiment, the Blazor team ran into an issue where some Azure SDKs did not support Blazor WASM yet. This forced them to choose between writing their own implementation using the Azure REST API or using JavaScript libraries and calling them through JavaScript interop in Blazor.The React team had to rely on the NPM repository, which provides most JavaScript third-party libraries. Sadly, many third-party libraries also depend on other third-party libraries, which again depend on many others, making dealing with security vulnerabilities deep in the dependency chain very difficult. The React team was struggling to deal with some high risk vulnerability warnings that could not be dealt with, due to one package deep within the Webpack dependency chain, which had been abandoned and thus had not updated it’s vulnerable dependencies. The only solutions for this problem are to either wait for the Webpack community to resolve this problem, or contribute to a library project yourself with a suitable fix. On the other hand, it was quite easy for the React team to find additional open source third-party libraries, to speed up development.To conclude this research, the teams have tallied up the pros and cons and concluded them into a final overview:As can be seen from the outcome, both technologies score relatively close, as both have strengths in different areas. This knowledge is very useful for us as a team since it allows us to come up with scenarios in which we would select a specific tool. In a case where a customer would solely be working with C#/.NET and would have increased concerns with regards to security, we would be more inclined to select Blazor as a technology, while if JavaScript is already part of the ecosystem and rapid development is more essential, React would be the better choice. Since our team is more proficient in C#, we have picked that technology as preferred, although we are also accepting React for specific scenarios, e.g., when a customer prefers a JavaScript/TypeScript frontend, because it fits their current stack better. The next step in this process as a team is to write a more detailed flowchart about when to use each technology.As a closing note, it is always important to remember when selecting technologies, prior to comparing, it should be clear what your requirements are for a specific technology and what problem you are trying to solve with it. In addition, always include the entire team when making decisions on tools and technologies, to increase the willingness to adopt a technology.----ITNEXTI work as a Cloud Software Developer. I enjoy working with Cloud and modern web technologies such as .NET, TypeScript and React.Mahdi MallakiinITNEXT--6Jacob FerusinITNEXT--8Martin HeinzinITNEXT--7Mirza LekainITNEXT--5Benjamin Nguyen--Robert Maier-Silldorff--4Rico FritzscheinLevel Up Coding--fatfishinJavaScript in Plain English--6Igor SnitkininITNEXT--2Yuvaraj S--HelpStatusAboutCareersBlogPrivacyTermsText to speechTeams



This post first appeared on VedVyas Articles, please read the originial post: here

Share the post

Beyond JavaScript: Exploring .NET Blazor’s Challenge to React

×

Subscribe to Vedvyas Articles

Get updates delivered right to your inbox!

Thank you for your subscription

×