Sitemap
Anas pk

Anas pk

I'm Anas pk, a freelance MERN Stack developer passionate about creating stellar web experiences.

React Features

5 min readJan 24, 2024

--

Press enter or click to view image in full size

Declarative over imperative style

Component-based architecture

Powerful abstractions

  • Declarative Style Benefits:
  • Reduces Complexity: Focuses on describing what should be done rather than detailing how to do it, leading to simpler and more readable code.
  • Improved Readability: Makes code easier to understand as it expresses the developer’s intent without delving into low-level implementation details.
  • Easier Maintenance: Changes and updates are typically simpler to implement since developers work at a higher level of abstraction.
  • Distinctions between Imperative and Declarative Styles:
  • Statements vs. Expressions:
  • Imperative: works with independent statements to advance program state.
  • Declarative: Uses expressions that build upon each other to progress the logic flow.

Reserved Word Usage:

  • Imperative: Relies on reserved words like for, while, switch, if, and else.
  • Declarative: utilizes array methods, arrow functions, object access, Boolean expressions, and ternary operators.

Function Composition:

  • Imperative: Uses independent function calls and method invocations.
  • Declarative: Leverages function composition to build upon previous expressions and create small, generalized pieces of logic.

Mutability:

  • Imperative: often uses mutable objects and manipulates existing structures.
  • Declarative: emphasizes immutable data, creating new structures from old ones rather than modifying existing ones.

Complexity Warning:

  • Academic Complexity: Declarative programming, when taken to extremes, can become complex, especially if advanced concepts like monads and functors are involved.

code example

  • Let’s create a simple example to illustrate these different points. The goal of this task is to create a function, countGoodPasswords, that, given a list of passwords, will return how many of the passwords are good. Here, we’ll define a good password as any password at least nine characters long

Imperative Solution:


function countGoodPasswords(passwords) {
const goodPasswords = []; // ❶ New statement changes the program state
for (let i = 0; i < passwords.length; i++) {
const password = passwords[i]; // ❶
if (password.length < 9) { // ❷ Reserved word controls program flow
continue; // ❷
}
goodPasswords.push(password); // ❶❸ Mutates an existing object
}
return goodPasswords.length;
}

Declarative Solution:


function countGoodPasswords(passwords) {
return passwords.filter(p => p.length >= 9).length;
}

Imperative Approach:

  • New statement changes the program state (❶): Declaration of an empty array (goodPasswords) that will be mutated in the loop.
  • Reserved word controls program flow (❷): The if statement controls the flow, using continue to skip processing if the password is too short.
  • Mutates an existing object (❶❸): The goodPasswords.push(password) statement mutates the existing array.

Declarative Approach:

  • One-liner using the filter and length methods.
  • Filtering (p => p.length >= 9): Uses a functional approach to create a new array with only passwords satisfying the length condition.
  • Length of the filtered array is returned directly.

Relationship to React:

  • React adopts a declarative approach when composing UIs.
  • Developers describe UI elements declaratively, and React manages updates when there are changes.
  • React’s declarative style is convenient when handling changes in the internal state of a view.

In React, the declarative style shines when making changes to the view, and React automatically updates the view in response to changes in state.

Component-based architecture using pure JavaScript

  • Component-Based Architecture (CBA):
  • Pre-dates React: CBA was in use before React, emphasizing separation of concerns, loose coupling, and code reuse.
  • Benefits: Provides advantages such as modularity, maintainability, and easier code reuse.
  • Building Block: In React, the component class is a fundamental building block of CBA.
  • Code Reuse: Code reuse is a significant benefit, allowing developers to write less code for similar functionality.

React’s Virtual DOM:

  • Purpose: Used to identify differences between the current view in the browser and the new view.
  • Process: React performs DOM diffing or reconciliation to bring the state and view back to similarity.
  • Automatic Updates: Developers update the state, and React automatically handles the view updates based on the identified differences.

DOM Diffing and Reconciliation:

  • Concept: The process of finding and applying the differences between the current DOM and the desired DOM.
  • Automatic View Updates: Developers focus on updating the state; React takes care of updating the view to reflect the state changes.
  • Avoiding Direct DOM Manipulation: Developers don’t directly manipulate the DOM; React manages the necessary changes implicitly.

source

. “Reconciliation,” on the React website (https://legacy.reactjs.org/docs/reconciliation.html)

Get Anas pk’s stories in your inbox

Join Medium for free to get updates from this writer.

. “React’s Diff Algorithm” by Christopher Chedeau (https://calendar.perfplanet.com/2013/diff/)

Comparison on the Framework Help Scale:

  • Plain JavaScript (No framework):
  • No Help: Without a framework, developers are on their own for managing updates and DOM manipulation.
  • Using jQuery:
  • DOM Manipulation Easier: jQuery makes DOM manipulation easier compared to plain JavaScript.
  • Manual View Updates: However, developers must manually handle view updates when data changes.
  • React’s Assistance:
  • Automatic View Updates: React provides assistance by automatically updating the view based on state changes.
  • Framework Support: Positioned on the scale towards providing significant help to developers, reducing the manual effort of managing updates.

Powerful abstractions

  • React provides powerful abstractions that simplify the life of a React developer

1.Synthetic events abstracting out browser differences in native events

2. JavaScript XML (JSX): abstracting out the JS DOM

3. Browser independence, allowing rendering in nonbrowser environments (e.g., on the server)

Synthetic events abstracting out browser differences in native events

  • Abstraction of Underlying Interfaces:
  • React abstracts the browser event model, concealing the complexities of native event interfaces.
  • Provides a simplified and consistent approach to handling events across different browsers.
  • Normalized/Synthesized Methods and Properties:
  • When using React events like onClick, React provides normalized/synthesized methods and properties.
  • Abstracts away browser-specific differences, ensuring a consistent experience regardless of the user’s browser.
  • Synthetic Event Objects:
  • Instead of native browser-specific event objects, React passes synthetic event objects to event handlers.
  • Synthetic events act as wrappers around native events, offering a unified interface for event handling.
  • Consistent Behavior Across Browsers:
  • React’s synthetic events ensure uniform behavior across various browsers, eliminating cross-browser compatibility concerns.
  • Developers can write event-handling code confidently, expecting the same outcomes in different environments.
  • Touch Events for Mobile Development:
  • React extends its synthetic events to touch events, catering to the needs of mobile app development.
  • Ideal for creating responsive and consistent web applications on touch-enabled devices.

JSX in React:

  • Controversial Nature:
  • JSX, a syntax extension for JavaScript, is a topic of debate in the React community.
  • Some see it as a strong argument for using React, while others find it challenging or even discouraging.
  • Advantages of JSX:
  • JSX acts as syntactic sugar on top of JavaScript, allowing the writing of React elements with HTML-like notation using < >.
  • Enhances code readability and implementation capabilities for developers.

JSX Compilation:

  • JSX is a mini-language compiled into native JavaScript, offering improved syntax and features.
  • Unlike regular JavaScript, JSX isn’t run on the browser; it serves as source code for compilation.
  • Example Snippet in JSX:
jsxCopy code if (user.session) {  
return <a href="/logout">Logout</a>;
} else {
return <a href="/login">Login</a>; }
  • JSX helps in expressing UI components in a more intuitive way, making code cleaner and more manageable.
  • Optional Usage:
  • JSX is optional, and developers can choose not to use it in their React projects.
  • Initial adjustment might be required due to the unconventional mix of HTML within JavaScript code.

DOM Abstraction and Server-Side Rendering:

  • Rendering on the Server:
  • React’s abstraction extends to rendering elements on the server, offering benefits for SEO and performance.
  • Allows for server-side rendering, enhancing search engine optimization and overall page load performance.
  • Rendering Options:
  • Various options exist for rendering React components in both the DOM and HTML strings on the server.
  • Hybrid approaches, involving rendering templates on the server and rehydrating with live data in the browser, are viable.
  • Performance Benefits:
  • React is renowned for its impressive performance, a sought-after advantage for developers.
  • The ability to optimize rendering on the server contributes to React’s efficiency in handling complex UIs.

--

--