The return of ECMAScript 2023 (and Angular)

#​634 — April 13, 2023

Read on the Web

JavaScript Weekly

The JavaScript Equality Table GameMinesweeper will feel like a walk in the park after this reminder of the horrors of JavaScript’s ==. If you need to go in depth, Section 7.2.14 of the ECMAScript spec will help, but otherwise? Stick to three equals (===) unless you have a good reason not to.

Reinis Ivanovs

htmx 1.9 Released — htmx (homepage) is an increasingly popular library outside of the JavaScript space as it lets folks use things like WebSockets, SSE, AJAX, and CSS transitions by marking up HTML rather than writing lots of JavaScript. v1.9 adds support for view transitions and generalized inline event handling. The code examples are worth a look – htmx makes a lot possible, with rather little tooling or markup needed.

htmx team

Supercharge AWS S3 Video Streaming with ImageKit’s Video API — Get adaptive bitrate streaming, video optimizations, format conversions, and real-time transformations and watermarking by attaching ImageKit with your AWS S3 bucket.

ImageKit sponsor

The ECMAScript® 2023 Language Spec Steps Forward — After prematurely announcing the progression of the ES2023 spec in February, we can now announce: TC39 has approved the ECMAScript 2023 spec, and while it remains a candidate, it’s now a step closer to eventual ECMA General Assembly approval. The finished proposals list for 2023 now includes Array find from last, hashbang support, Symbols as WeakMap keys, and change Array by copy.

ECMA International

IN BRIEF:

▶️ Angular is back with a vengeance, says Fireship.

Serverless platform AWS Lambda has introduced response streaming on its JS runtime (for now) so you can send response data as it becomes available rather than all at once. (→ Via Serverless Status)

/[]/ A look at a seemingly JS-specific quirk in regular expressions when empty character classes are used.

An analysis of languages used in GitHub pull requests shows JavaScript/TypeScript leading the way with Python just slightly behind. The comments went in lots of odd directions here.

Seven folks at Vue Amsterdam 2023 shared their ▶️ tips on getting started with Vue.js.

▶️ An hour-long chat on the State of Node.js with some leading figures.

Node v18.16.0 (LTS) has been released with backported support for compiling JavaScript code into a single executable app. Node 19’s Ada URL parser also appears.

A striking visual introduction to React and its fundamental concepts.

RELEASES:

Node.js v19.9 (Current)

Puppeteer v19.9 – It’s the week for almost 20s.

pnpm 8.2 – Efficient npm alternative.

Redwood 4.5 – Popular app framework.

Storybook 7.0 – With an official release post this time.

???? Articles & Tutorials

Ranger: Use a Range-Like Syntax for Anything? — const numbers = 1[[…8]], anyone? This is a neat trick for a bit of syntatic sugar, but I’m not sure it would pass the sniff test for most teams. You might find the implementation interesting to check out though. Long may this sort of experimentation continue.

Jon Randy

???? A proposal for JavaScript to get built-in range support is at stage 2.

????  Build and Deploy ‘23: May 3rd – Save the Date! — The ultimate CI/CD virtual conference – best practices and end-user success stories from DevOps experts. Plus, a keynote from Emily Freeman, author of DevOps for Dummies.

Codefresh sponsor

Trying Node’s Built-In Test Runner — In 2022, Node gained an experimental built-in test runner (node:test). It’s going to become stable in the forthcoming Node v20, so it’s a good time to look at how it works and how it compares to other solutions you might already be using.

Gleb Bahmutov

▶  The Right Way To Merge JavaScript Objects — In just one minute, too.

Jack Herrington

Ref vs. Reactive: What to Choose When Using Vue 3 Composition API?

Michael Hoffmann

How to Stream File Uploads to S3 Object Storage from Node.js

Austin Gil

How to Contribute to a Project You Have No Idea About

Michal Warda

???? Code & Tools

Reveal.js 4.5: An HTML Presentation Framework — Brings elegant presentations to anyone with a Web browser. v4.5 was just released with support for jumping to specific slides, a few new themes, and with live reload working with files in subfolders.

Hakim El Hattab

List.js: Add Search, Sort, Filters, and More to Tables and Lists — A handy library for adding search, sort, filters and flexibility to tables, lists or other HTML elements. Want an example? Why, of course.

Jonny Strömberg

????Quokka.js – #1 JavaScript Scratchpad for VS Code — With 2M+ downloads, Quokka.js is the #1 tool for exploring and testing JavaScript/TypeScript. Code runs immediately as you type.

Wallaby.js sponsor

Queue: Async Function Queue with Adjustable Concurrency — Exports a class Queue that implements most of the Array API.

Jesse Tane

Yet Another React Lightbox — Add a lightbox component to your projects “in minutes” – there are several examples to try, as well as a playground with adjustable settings. GitHub repo.

Igor Danchenko

Sandpack 2.6: Component Toolkit for Creating Live Code Editing Experiences — Created by the folks at CodeSandbox, so they surely know what they’re doing in this space. GitHub repo.

CodeSandbox

Easy to Use, Full-Stack Application Monitoring

TelemetryHub sponsor

TS Writer: A Template String Template Engine for Generating Code at Runtime — Rather niche, but aimed at situations where you might need to generate code at runtime in TypeScript.

tinylibs

Minimatch 9.0
↳ Glob matcher library.
     minimatch(“bar.foo”, “*.foo”)

hls.js 1.4
↳ Play HLS in browsers with support for MSE.

Partytown 0.8
↳ Relocate third-party scripts off the main thread.

Plasmo 0.68
“It’s like Next.js for browser extensions”

Obsidian 8.0 – GraphQL, built for Deno.

MUI X 6.1 – React component suite.

TestCafe 2.5 – Automate end-to-end web testing.

Maquette 3.6 – Lightweight virtual DOM library.

Venom 5.0 – WhatsApp bot library.

???? Jobs

Find JavaScript Jobs with Hired — Hired makes job hunting easy-instead of chasing recruiters, companies approach you with salary details up front. Create a free profile now.

Hired

Full Stack JavaScript Engineer @ Emerging Cybersecurity Startup — Small team/big results. Fun + flexible + always interesting. Come build our award-winning, all-in-one cybersecurity platform.

Defendify

????‍???? Got a job listing to share? Here’s how.

Flatlogic Admin Templates banner

12+ Best Node.js Frameworks for Web App Development in 2022

Node.js is getting increasingly popular among developers, to the point where some developers call Node.js their primary choice for backend development. In this article, we review the 12 best Node.js web frameworks that we rate according to their popularity and unique toolkits for time and cost-efficiency.

Is Node.js a web framework?

So is Node.js a web framework? The most common way of referring to it is as a web framework. Still, Node.js is a JavaScript execution environment – a server-side platform for JavaScript code execution and portability. Instead, web frameworks focus on building features. A lot of developers have built Node.js web frameworks, such as Nest.js, Express.js, and other toolkits, for Node.js applications, providing a unique experience for software developers.

What are Node.js web frameworks?

Every web application technology offers different types of frameworks, all supporting a specific use case in the development lifecycle. Node.js web frameworks come in three types – Full-Stack Model-View-Controller (MVC), MVC, and REST API web frameworks.

Node.js web framework features

API of Node.js is asynchronous. You can use the Node.js server to move after a data request, rather than waiting for the API to return the information.
The code execution process of Node.js is faster compared to the reverse backend framework.
Node.js runs on a single-threaded model.
With Node.js web framework developers never face buffering issues because it transfers information by parts.
It is supported by Google’s Node.js runtime environment.

Through these features, it is clear to understand why developers more often choose Node.js for Backend development. Let’s take a closer look at each Node.js web framework.

NestJS

Github repo: https://github.com/nestjs/nest
License: MIT
Github stars: 47400

NestJS is object-oriented and functional-reactive programming (FRP), widely used for developing enterprise-level dynamic and scalable web solutions, being well featured with extensive libraries.

NestJS is based on TypeScript as its core programming language, but is also highly compatible with a JavaScript subset and easily integrated with other frameworks such as ExpressJS through a command-line interface.

Why use NestJS:

Modern CLI
 functional-reactive programming
Multiple easy-to-use external libraries
Straightforward Angular compatibility

NestJS has a clean and modular architecture pattern aiding developers to build scalable and maintainable applications with ease. 

Pros of NestJS:

Powerful but super friendly to work with
Fast development
Easy to understand documentation
Angular style syntax for the backend

NodeJS ecosystem
Typescript
Its easy to understand since it follows angular syntax
Good architecture
Integrates with Narwhal Extensions
Typescript makes it well integrated in vscode
Graphql support easy
Agnosticism
Easily integrate with others external extensions

ExpressJS

Github repo: https://github.com/expressjs/express
License: MIT
Github stars: 57200

ExpressJS is minimalistic, asynchronous, fast, and powerful and was launched in 2010. It’s beginner-friendly thanks to a low learning curve that requires only a basic understanding of the Node.js environment and programming skills. ExpressJS optimises client-to-server requests and observed user interaction via an API very quickly, and also helps you manage high-speed I/O operations. 

Why use ExpressJS:

Enhanced content coordination
MVC architecture pattern
HTTP helpers
Asynchronous programming to support multiple independent operations

ExpressJS offers templating, robust routing, security and error handling, making it suitable for building enterprise or browser-based applications.

Pros of ExpressJS :

Simple
NodeJS
Javascript
High performance
Robust routing
Middlewares
Open source
Great community
Hybrid web applications
Well documented
Light weight

Meteor

Github repo: https://github.com/meteor/meteor
License: MIT
Github stars: 42900

Meteor is an open-source framework that was launched in 2012 that works best for teams who want to develop in a single language, being a full-featured Node.js web framework. Meteor is ideal for modern real-time applications as it facilitates instant data transfer between server and client.

Why use Meteor:

Cross-platform web framework
Rapid prototyping using the CLI
Extensive community support and open-source code
End-to-end solution
Seamless integration with other frameworks

The Meteor is an excellent option for those who are familiar with Javascript and prefer it. It’s a great one for both web and mobile app development as well. Meteor is great for applications that require a lot of updates that need to be sent out, even in a live environment.

Pros of Meteor :

Real-time
Full stack, one language
Best app dev platform available today
Data synchronization
Javascript
Focus on your product not the plumbing
Hot code pushes
Open source
Live page updates
Latency compensation
Ultra-simple development environment
Great for beginners
Smart Packages

KoaJS

Github repo: https://github.com/koajs/koa
License: MIT
Github stars: 32700

Koa has been called the next-generation Node.js web framework, and it’s one of the best of the bunch. Koa uses a stack-based approach to handling HTTP mediators, which makes it a great option for easy API development. Koa is similar to ExpressJS, so it’s fairly easy to switch from either one. Despite the same features and flexibility, Koa reduces the complexity of writing code even more.  

Why use Koa:

Multi-level customisation
Considered a lightweight version of ExpressJS
Supplied with cascading middleware ( user experience personalisation)
Node mismatch normalization
Cleans caches and supports content and proxy negotiation

Use Koa when performance is the main focus of your web application. Koa is ahead of ExpressJS in some scenarios, so you can use it for large-scale projects. 

Pros of Koa :

Async/Await
JavaScript
REST API

socket.io

Github repo:https://github.com/socketio/socket.io
License: MIT
Github stars: 55900

The socket is a Javascript library that works most effectively for real-time web applications. The socket is used when communication between real-time web clients and servers needs to be efficiently bidirectional. 

Why use socket.io:

Binary support
Multiplexing support
Reliability
Auto-reconnection support
Auto-correction and error detection 

The socket is a great choice when building real-time applications like video conferencing, chat rooms and multiplayer games with servers being required to send data out before it’s requested from the client-side.

Pros of socket :

Real-time
Event-based communication
NodeJS
WebSockets
Open source
Binary streaming
No internet dependency
Large community

TotalJS

Github repo: https://github.com/totaljs/
License: MIT
Github stars: n/a

TotalJS is a web framework that offers a CMS-like user experience and has almost all the functionality you need in a Node.js environment. The framework is a full open-source framework that provides developers with the ultimate flexibility. There are various options available for the framework, e.g. CMS, and HelpDesk. Through these options, your application will have more integration possibilities with the REST service and hyper-fast, low-maintenance, stable applications. 

TotalJS is most well-known for its real-time, high-precision tracking in modern applications. 

Pros of TotalJS:

Tracking in real-time
API Testing
Automatic project discovery
Compatibility with multiple databases
Flexibility to work with different frontend frameworks
Fast development and low cost of maintenance

SailsJS

Github repo: https://github.com/balderdashy/sails
License: MIT
Github stars: 22247

SailsJS is similar to the MVC architect pattern of web frameworks such as Ruby on Rails, and it supports modernized data-centric development. Compatible with all databases, at the same time it flexibly integrates Javascript frameworks. SailsJS is the most relevant framework for building high-quality custom applications. Its special code-writing policy helps reduce the code needed, allowing you to integrate npm modules while remaining flexible and open source. 

Pros of SailsJS:

REST API auto-generation
Multiple security policies
Frontend agnosticism
Object Relational Mapping for framework databases compatibility
Supports ExpressJS integration for HTTP requests and socket.io for WebSockets 

FeathersJS

Github repo: https://github.com/feathersjs/feathers
License: MIT
Github stars: 14000

FeathersJS is gaining popularity between website and application developers because it provides flexibility in development with react native as well as Node.js. It is a framework of microservices because it operates with more than one database, providing real-time functionality. FeathersJS makes it easier for web developers to code concretely and understandably.

Pros of FeathersJS:

Reusable services
Modern CLI
Automated RESTful APIs
Authentication and authorization plugins by default
Lightweight

FeathersJS natively supports all frontend technologies, and its database-agnostic is best performed in a Node.js environment because the web framework supports Javascript and Typescript. It allows you to create production-ready applications and real-time applications, and also REST APIs in just a few days.

hapi.dev

Github repo: https://github.com/hapijs/hapi
License: MIT
Github stars: 13900

Hapi is an open-source framework for web applications. It is well-known for proxy server development as well as REST APIs and some other desktop applications since the framework is robust and security-rich. It has a wealth of built-in plugins, therefore this means you don’t have to worry about running non-official middleware. 

Pros of Hapi:

Extensive and scalable applications
Low overhead
Secure default settings
Rich ecosystem
Quick and easy bug fixes
Compatible with multiple databases
Compatible with Rest API and HTTPS proxy applications
Caching, authentication and input validation by default

AdonisJS

Github repo: https://github.com/adonisjs/core
License: MIT
Github stars: 12600

AdonisJS is a Model-View-Controller Node.js web framework based on a structural template repeating Laravel. The framework decreases the time required for development by focusing on core details such as out of the box web socket support, development speed and performance, lifecycle dependency management, and built-in modules for data validation, mailing, and authentication. Command-based coding structure and the interface is easy for developers to understand. The Node.js web framework uses the concepts of dependency injections through IoC or control inversion. It offers developers an organized structure for accessing all the components of the framework. 

Pros of AdonisJS:

Organised template with folder structure
Easy user input validation.
Ability to write custom functional testing scripts
Support for Lucid object-relational mapping.
Threat protection such as cross-site forgery protection

Loopback

Github repo: https://github.com/loopbackio/loopback-next
License: MIT
Github stars: 4200

Loopback provides the best connection with any Node.js web framework and can be integrated with multiple API services. You can best use the platform to build REST APIs with minimal lead time. Loopback offers outstanding flexibility, interfacing with a broad range of browsers, devices,  databases, and services. Framework’s structured code helps support application modules and speed of development. Loopback has the best documentation, allowing even beginners to work with it. 

Pros of Loopback:

Comprehensive support for networked applications
The built-in client API explorer
High extensibility
Multiple database support
Clean and modular code
Full-stack development
Data storage, third-party access, and user management

Loopback is designed solely for creating powerful end-to-end APIs and handling requests for them. 

DerbyJS

Github repo: https://github.com/derbyjs/derby
License: MIT
Github stars: 4622

DerbyJS is a full-stack web application development platform powered by Node.js technology. This framework uses the Model-View-Controller architecture with an easy-to-write nomenclature for coding. This framework is great for building real-time web applications since it allows essentially the same code to work on Node.js and in the browser. That way, you don’t have to worry about writing separate codes for the view part. DerbyJS decreases the delay in content delivery by rendering a client-side view on the server. Performing this makes the application SEO-friendly and improves the user experience. 

Pros of DerbyJS:

Support for Racer Engine
Real-time conversion for data synchronization
Offline use and conflict resolution support

Version control
Client-side and server-side code sharing
Rendering client-side views on the server-side

Conclusion

Node.js web frameworks make application development easier with their enormous possibilities for the advancement of web and mobile application development.  Under the conditions of increasingly growing technologies, a thorough investigation of project requirements and accessibility of resources is the key to choosing the right web framework that will provide the greatest results.

The post 12+ Best Node.js Frameworks for Web App Development in 2022 appeared first on Flatlogic Blog.Flatlogic Admin Templates banner

Vue Material Admin Update

Right after we have updated React Material Admin we also do the same with Vue Material Admin.

What products are affected by the update?

The update was released on 3 products:

Vue Material Admin Full
Vue Material Template Node.js
Vue Material Laravel Template

What has changed?

The main changes are in updated dependencies. We also updated the version of Vuetify as the Vue Material Admin based on it. So here is the list of main updates:

✅ amcharts/amcharts4: 4.10.22 -> 4.10.25
✅ amcharts/amcharts4-geodata: 4.1.22 -> 4.1.23
✅apexcharts: 3.29.0 -> 3.35.3
✅ axios: 0.23.0 -> 0.27.2
✅ core-js: 3.19.0 -> 3.22.7
✅ moment: 2.29.1 -> 2.29.3
✅ vue-router: 3.5.2 -> 3.5.3
✅ vue-apexcharts: 1.6.0 -> 1.6.1
✅ vuetify: 2.5.10 -> 2.6.6

So the Vue Material Admin is up-to-date and we would be really happy if you choose it for your future projects. You don’t need to spend your time updating all those technologies by yourself, so you can focus on developing business features.

Moving forward and Summing Up

We will be constantly updating all of our Vue templates as new libraries will release. And for sure sometime release one of our templates on Vue 3.

For the rest of our Vue templates, check our marketplace. If you face any difficulties setting up this or that template or admin dashboard, please feel free to leave us a message on our forumTwitter or Facebook. We will respond to your inquiry as quickly as possible!

Happy coding!

The post Vue Material Admin Update appeared first on Flatlogic Blog.Flatlogic Admin Templates banner

Functional Components vs. Class Components in React.js

The history of React.js components
Functional components in React
Class components in React.js
The difference between functional and class components
Bonus: Building an App with Flatlogic Platform

When you start to code with React you may get confused by some things in React, like JSX syntax or the difference between functional and class components. JSX is an interesting syntax extension to JavaScript that was developed to make the process of writing the UI elements more comfortable. The development with React doesn’t require using JSX, just like our article is not about it either. We are going to discuss Functional vs Class components. Let’s start.

The history of React.js components

We should jump into the history of React first to understand how React components evolved. React, created by Facebook software engineer Jordan Walke, is an open-source front-end JS library for building interactive user interfaces. The first release was in 2013, with 0.3.0 version. React has got further development and updated several times every year. The React team added more and more new features to the library to give developers more tools for coding. Among the most famous and loved features are the virtual DOM, one-way data-binding, JSX, reusable components, declarative programming, stable code, fast rendering of UI elements, great performance optimization opportunities. The current version at the time of writing this article is 17.0.1.

Along with all these benefits React offered it also gave developers two types of components they could use to create UI components. It can be supposed that both types of components provide the same opportunities for writing UI elements, and the choice depends only on the developer’s preferences. Well, it wasn’t true. The real situation was that class components were the only viable option to develop complex apps with React. The reason was that using class components you get a large number of capabilities, for example, state, while functional components didn’t provide such an option. However, the situation changed when React v.16.8 was released in 2019. A new version contained an update that was meant to take the development with functional components to the next level. React offered Hooks for functional components. The introduction of Hooks made it possible to write the entire complex application using only functions as React components. This is a deeply significant event that changed the way of React apps development. Keeping that in mind, we are going back to the present time and find out what is happening now and what functional and class components are.

Functional components in React

Functional components in React are just JavaScript functions like this:

function Foo(props) {
return <h1>Who is living young, wild, and free? – {props.name}</h1>;
}
const element = <Foo name=”Me!” />;
ReactDOM.render(element, document.getElementById(‘home’));

In our case, we render an element that represents the user-defined component called Foo. The element passes JSX attribute name=” Me” as a prop to our function component Foo, which returns a <h1>Who is living young, wild, and free? – Me!</h1> element as the result.

Props are inputs for both types of components. One of the main tasks of props is to pass information from component to component. It’s especially necessary if you want to build a dynamic user interface. However, there is one important rule that you shouldn’t forget: props are read-only. That means that all React components shouldn’t change their inputs and the same props must return the same result. Components that respect their props are called “pure”. That rule works both for class and function components. 

JSX is a special extension that allows us to place HTML elements right inside JavaScript code without using additional methods like createElement(). All your HTML tags will be converted into React elements after compilation. JSX may be convenient, however, it is an optional instrument for development. To see how the same blocks of code look like with/without using JSX try the online Babel compiler

Another way of writing function components is by using an arrow function.

An example of an arrow function:

const App = () => { //that is an arrow function
const greeting = ‘Hello Function Component!’;

return <Headline value={greeting} />;
};

const Headline = ({ value }) =>
<h1>{value}</h1>;

export default App;

Arrow functions have some benefits: 

The code written with arrow functions looks compact. Functions are easier to write and read. One of the reasons is an implicit return by simply omitting the curly braces (see video with an example).
Arrow syntax doesn’t contain its context and automatically bind this to the surrounding code’s context 

But since arrow functions give one more way to write code (along with standard functions and classes) you need to set rules when we use any of them. As an example you can stick to the following rules:

If you work with global scope and Object.prototype properties use function.
If you work with object constructors use class.
If you face any other situation use arrow function.

The examples above are called stateless function components because they just take props as an argument and return a react element. They don’t manage state and don’t have a lifecycle, while class components do. However, you can use Hooks with them that allow you to work with state and lifecycle and add even more features. We will speak about that in the comparison below.

Class components in React.js

Let’s start with an example:

class Foo extends React.Component {
render() {
return <h1>Who is living young, wild, and free? – {this.props.name}</h1>;
}
}

It is a regular ES6 class that extends the component class from the react library. To return HTML you have to use render() method in it. 

Class components work fine with props as well as functional components do. To pass the props to a component you can use a syntax similar to HTML attributes. In our sample case we need to replace props.name with this.props.name in the render() body to use props. 

Additional benefits class components offer by default are state and lifecycle. That is why class components are also known as “stateful” components. 

The state of a component is an observable object that holds some information and controls the behavior of the component. The difference between props and state is that props don’t change over time during the lifetime of a component. The state holds the data that can be changed over time and changes the component rendering as a result.

The state of a component is supposed to have the initial this.state that can be assigned with a class constructor. The class constructor is a special JavaScript method that allows to bind event handlers to the component or to initialize the local state of the component. 

If you don’t need to handle any of both cases above the implementation of a constructor is unnecessary. Example of a constructor:

constructor(props) {
super(props);
this.state = {};
}

Constructor() function inside a React component requires super(props) before any other statement. Super(props) is a reference to parents constructor() functionthat React.Component base class has. When we define a new constructor() inside a class component, we replace the base constructor() function. However, it has some code inside of it we still need. So to get access to that code we call super(props) – that is why we have to add super(props) every time we define a constructor() inside a class component. The constructor() is called before the React component is mounted. To use state in a class component we must define the initial state of it in the constructor. Instead of calling setState(), we need to assign the initial state with this.state command in the constructor. It’s the only case when we are allowed to change the state directly by assigning its value, otherwise use setState() instead. Constructor() has other rules you should be aware of, you can read about them on the link

Differentiating Functional vs Class components

1.State and lifecycle

Well, the standard answer to the question about the difference between functional and class components was that class components provide developers with such features as setState() and lifecycle methods componentDidMount(), componentWillUnmoun(), etc., while functional components don’t. That was true because functional components are plain JavaScript functions that accept props and return React elements, while class components are JavaScript classes that extend React.Component which has a render method. Both state and lifecycle methods come from React.Component, so they were available only for class components. The widespread advice was something like that: “Go with functional if your component doesn’t do much more than take in some props and render”. You had no options on how to build complex UI and class components dominated in React development for a while.

However, that has changed with the introduction of Hooks. To replace setState method to work with the state in class components React offers useState Hook.

To work with components lifecycle classes have such methods like componentDidMount, componentWillUnmount, componentWillUpdate, componentDidUpdate, shouldComponentUpdate. Functional components have got a tool to work with the same methods using only one Hook useEffect. You can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined. 

Standard class methods work well but do look not very elegant. Functional components offer an elegant and simple decision: instead of using multiple lifecycle methods, we can replace them with one Hook useEffect. What React developers write about Hooks:

“Our goal is for Hooks to cover all use cases for classes as soon as possible. There are no Hook equivalents to the uncommon getSnapshotBeforeUpdate, getDerivedStateFromError and componentDidCatch lifecycles yet, but we plan to add them soon. It is an early time for Hooks, and some third-party libraries might not be compatible with Hooks at the moment.”

an official React documentation

So Hooks are more addition to functional components rather than a replacement of class components.

2. Syntax

The obvious difference is the syntax. Let’s examine several examples.

How we declare components.

Functional components are JavaScript functions:

function FunctionalComponent() {
return <h1>Hello, world</h1>;
}

Class components are classes that extend React.Component:

class ClassComponent extends React.Component {
render() {
return <h1>Hello, world</h1>;
}
}

To return our h1 we need the render() method inside a class component. 

The way we pass props.

Let’s say we have props with the name “First”.

<Component name = “First” />

Working with functional components, we pass the props as an argument of our function using the construction “props.name”. 

function FunctionalComponent(props) {
return <h1>Hello, {props.name}</h1>;
}

With class components, we need to add this. to refer to props.

class ClassComponent extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}

Handling state.

To handle state functional components in React offer useState()Hook. We assign the initial state of count equal to 0 and set the method setCount() that increases it by one every time we click a button. The component returns the number of times we clicked the button and the button itself. The initial state is used only during the first render. The type of argument can be a number, string, object, or null. To learn more about that useState() Hook see the official documentation.  

const FunctionalComponent = () => {
const [count, setCount] = React.useState(0);
return (
<div>
<p>count: {count}</p>
<button onClick={() => setCount(count + 1)}>Click</button>
</div>
);
};

Class components work a bit differently. They use setState() function, require a constructor, and this keyword. 

class ClassComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}

render() {
return (
<div>
<p>count: {this.state.count} times</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Click
</button>
</div>
);
}
}

The underlying logic is similar to the logic in functional components. In constructor() we declare a state object, state key “count” and the initial value equal to 0. In render() method we use setState() function to update the value of our count using this.state.count and the app renders the number of times the button was clicked and displays the button itself. The result is the same, but the same functionality requires more lines of code for class components. However, it doesn’t mean that the code written with class components will be more cumbersome than the code made with functional components, but the code definitely will be bigger.

Lifecycle methods.

With version 16.8 React allows working with lifecycle methods of components. That means that developers have better control over functional components and can manipulate their life phases (initialization or setting the initial state, mount, update, unmount). The initialization is explained in the paragraph above, let’s look at the next stage.

Mounting.

The useEffect Hook for functional components:

const FunctionalComponent = () => {
React.useEffect(() => {
console.log(“Hello”);
}, []);
return <h1>Hello, World</h1>;
};

The componentDidMount method for class components:

class ClassComponent extends React.Component {
componentDidMount() {
console.log(“Hello”);
}

render() {
return <h1>Hello, World</h1>;
}
}

The useEffect Hook possesses two parameters: the first is the “effect” itself that is going to be called once after every render of the component. The second parameter is an array of observable state or states (or so-called a dependency list). useEffect Hook only runs if one of these states changes. Leaving the second parameter empty useEffect Hooks runs once after render.

Updating.

The useEffect Hook for functional components:

function BooksList () {
const [books, updateBooks] = React.useState([]);
const [counter, updateCounter] = React.useState(0);

React.useEffect(function effectFunction() {
if (books) {
updateBooks([…books, { name: ‘A new Book’, id: ‘…’}]);
}
}, [counter]);

const incrementCounter = () => {
updateCounter(counter + 1);
}

}

The componentDidUpdate method for class components:

componentDidUpdate(prevProps) {
// Typical usage (don’t forget to compare props):
if (this.props.userID !== prevProps.userID) {
this.fetchData(this.props.userID);
}
}

As we have mentioned the second parameter in the useEffect hook is an array of observable states, once a counter changes it triggers the effectFunction hook.

Unmounting.

The useEffect Hook for functional components (yes, again):

const FunctionalComponent = () => {
React.useEffect(() => {
return () => {
console.log(“Bye”);
};
}, []);
return <h1>Bye, World</h1>;
};

The componentDidUnmount method for class components:

class ClassComponent extends React.Component {
componentDidMount() {
console.log(“Hello”);
}

render() {
return <h1>Hello, World</h1>;
}
}

3. Hoisting works only for functional components

Hoisting is a concept that appeared in ECMAScript® 2015 Language Specification. According to that concept, JavaScript moves variable and function declarations to the top that allows you to access a variable or a function first and only then declare it. Actually, JS doesn’t move the code, it puts declarations in memory during the compile phase that allows calling a function before you declare it. That is not true to classes, trying to get access to a class before the declaration throws a ReferenceError exception. 

An example of the code where we call function before its declaration: 

catName(“Tiger”);
function catName(name) {
console.log(“My cat’s name is ” + name);
}
// The result of the code above is: “My cat’s name is Tiger”

Even though we call the function before we write it, the code works great. The following code with class declaration will throw an error: 

const p = new MyName(); // ReferenceError
class MyName {}

That is not all. JavaScript only hoists declarations, not initialization. If we declare a variable and call it before the initialization it returns undefined. See example: 

console.log(myName); // Returns undefined, as only declaration was hoisted
var myName; // Declaration
myName = “John”; // Initialization

Initializations with keywords let and const are also hoisted, but not initialized. That means that your app is aware of the variable existence. However, it can’t use it until variable initialization. The example below will throw a ReferenceError:

myName = “John”;
let myName;

That example will not run at all:

myName = “John”;
const myName;

Why does it matter? Let’s get back to React and create a simple React app in index.js file with one component in a separate file Component.js:

import React from ‘react’;
import {render} from ‘react-dom’;
import App from ‘.Component’;render(
<App/>,
document.getElementById(“root”)
);

And the component itself:

const Component = () => {
return (
<div>Hello, React</div>
);
}
export default Component;

The app renders a text: “Hello, React”. Since the component is small, there is a sense not to separate it and merge it into index.js file like this:

import React from ‘react’;
import {render} from ‘react-dom’;
render(
<Component/>,
document.getElementById(“root”)
);
const Component = () => {
return (
<div>Hello, React</div>
);
}

And we get an undefined error because we try to render a component that was declared with an arrow function before we initialize it.To repair the code just re-order the declaration and put it before calling render().

4. The way they capture values (props)

One interesting experiment (the original article with full analysis can be found here) that took place on the Internet is the following React app.

It’s a simple app that simulates a social network request to follow someone. The app displays a drop-down list with three profiles to follow, static greetings text, and two buttons that call the confirmation alert to start following a chosen person. The confirmation alert appears 3 seconds later after you clicked the button. The delay is set with setTimeout() method. 

The list of the experiment is the following: 

Choose a profile to follow 
Click a follow button with “function” text in brackets near it
Change a profile to follow in the drop-down list before the confirmation alert appears 
Check the name in the confirmation alert 
Repeat the same four steps above for the follow button with “class” text in brackets

In the first case with the functional button switching the name doesn’t affect the confirmation alert. With the class button switching the name changes the alert message, even though you clicked to follow Dan but switched to Sophie, the alert message will be “Followed Sophie”. The correct behavior is the first, of course. No one likes to follow a wrong profile on social media.  

The reason for such a behavior lies in the essence of functional and class components. Let’s examine these lines of code:

class ProfilePage extends React.Component {
showMessage = () => {
alert(‘Followed ‘ + this.props.user); };

And:
function ProfilePage(props) {
const showMessage = () => {
alert(‘Followed ‘ + props.user);
};

As we have said props are read-only, they are immutable. So once you pass the props to a functional component ProfilePage(props), the only remaining task for React is to render it after the time is up. 

On the other hand, this is mutable. And it’s okay because it allows us to use states and lifecycle methods correctly. So if we pass other props while the alert message doesn’t appear, this.props.name. changes and showMessage method displays the last version of props. Our showMessage method is not tied to any particular render and that may become a problem. 

There are several potential solutions that actually work. One of them is to catch props at the time of render like this:

class ProfilePage extends React.Component {
render() {
// Capture the props!
const props = this.props;
// Note: we are *inside render*.
// These aren’t class methods.
const showMessage = () => {
alert(‘Followed ‘ + props.user); };

const handleClick = () => {
setTimeout(showMessage, 3000);
};

return <button onClick={handleClick}>Follow</button>;
}
}

So we stuck our certain props to a particular render().

5. Running tests 

There are two most popular instruments for running tests: Enzyme and Jest. Enzyme is a JavaScript testing utility for React that allows testing React components’ display. Jest is a JavaScript testing framework for writing tests, in other words, for creating, running, and structuring tests. 

These two instruments do a great job on both types of components. There are some specificities in running tests for functional components, like the fact, that state hooks are internal to the component and can’t be tested by calling them. However, instruments and methods are similar. 

6. Performance difference 

There is an opinion that functional components show a greater performance compared to class components. The point is that the React functional element is a simple object with 2 properties: type(string) and props(object). To render such a component React needs to call the function and pass props – that is all. 

Class components are more complex: they are instances of React.Component with the constructor in it and complicated system of methods for manipulating state and lifecycle. 

Theoretically, calling a function should take less time than creating an instance of a class. Well, one developer held a test: he rendered 10000 elements of stateless components and class components. You can see the result here. As we see from the 3 experiments there is no difference in render time between rendering class and functional components.

To sum up everything above: 

Сlass components were the only option to add states to components and manipulate lifecycle. However, it has changed since the introduction of Hooks, which gave the same opportunities to functional components as classes had. 
The major difference is the syntax. It relates to the way we declare components, pass props, handling states, manage lifecycle. 

Function components capture the props and state by default. It is not a bug, but a feature of functional components.

Functional components require less code to write an equal component. However, that doesn’t mean that functional components more readable and convenient to use. If a developer is used to work with object-oriented programming, he finds using class components much more comfortable. Those who are used to functional programming like functional components more than class components. 
There are two most popular tools to test functional and class components: Enzyme and Jest. They work great for both types of components. 
There is no big difference in render time between class and functional components. 

Today you can build a whole app using only functional components. It was impossible till 2019. That became possible thanks to Hooks. Does Hooks replace class components in the coming years? We don’t think so, because there are still some features that functional components can’t reproduce. And there will always be developers, who are used to working with objects rather than with functions. However, we await the growth in functional component popularity and an increase in the number of features for Hooks. And it’s likely that the functionality Hooks will provide goes beyond class components possibilities. 

Bonus: Building an App with Flatlogic Platform

Understanding Functional and Class components is an important stepping stone in React development. Crafting Apps by hand requires a thorough understanding of all the intricacies of the library. However, there’s a quicker way for those who aren’t technically adept or lack time to write the whole thing from the ground up. Some people need a unique App with functions not seen elsewhere, but most apps are different combinations of the same parts and features. We used that insight when developing the Flatlogic Platform.

Flatlogic Platform is a constructor-style tool for combining pre-built parts into brand-new applications. It requires a few steps from you. Keep reading to know what those are!

#1: Name the Project

This step is what it sounds like. The only valuable advice we can think of is to pick a name that is easy enough to associate with the project.

#2: Choose stack

Next up, choose the technologies your App’s parts will run on. Those are underlying technologies for back-end, front-end, and database. In this example, we’re picking a combination of React, Node.js, and MySQL. But all other combinations are perfectly compatible, too.

#3: Choose Design

You’ll have several design schemes to choose from. Some are transparent and light, others with a heavier feel. Pick the one you like, this part is purely aesthetical.

#4: Create the schema

The schema is the structure of a database. Names of fields, types of data, the way the App processes said data… Every aspect that defines how the database works is a part of the schema. It might be tricky at first, but you’ll get the hang of it. A thorough review of what your App is supposed to do will be helpful. If you’re short on time or unsure, pick one of the pre-built schemas. One of them is bound to suit your needs.

#5: Review and generate

The heavy decision-making is over. It’s time to check if every choice you’ve made is the way you want it to be and (assuming everything’s fine) hit “Finish”.

The compilation takes a couple of minutes on most devices. Upon completion, the Platform will offer you your very own App. Hit “Deploy”, host it locally in one click or push it to GitHub for further use or adjustment.

Flatlogic Platform helps create simple yet functional and smooth Apps for commercial and administrative purposes, make sure you give it a try! Happy developing and see you in the next articles!

You might also like these articles:

React.js vs. React Native. What are the Key Differences and Advantages?

Top 12 Bug Tracking Tools

Angular vs. Bootstrap – 6+ Key Differences, Pros, and Cons

The post Functional Components vs. Class Components in React.js appeared first on Flatlogic Blog.