Welcome to our blog!

Why Use Pure Functions in React Components?

Posted by:

|

On:

|

Image from Canva Pro

In the world of JavaScript, some functions are known as pure functions. These are special because they adhere to two main principles:

  1. Self-contained operations: Pure functions don’t interfere with or modify any objects or variables that existed before their invocation. This means they don’t produce any side effects in the rest of your code, keeping their operations clean and predictable.
  2. Consistent results: A hallmark of pure functions is that they always return the same result when given the same inputs, no matter how many times or when you call them. This predictability is a huge asset in software development.

Embracing pure functions when writing your components can drastically reduce confusing bugs and erratic behaviors in your application as it grows.

This approach encourages clarity and maintainability―ensuring that each part of your application behaves as expected.

However, not all components are pure, and here’s what happens with an impure component:

App.js

let guest = 0;

function Peter() {
// Bad: changing a preexisting variable!
guest = guest + 1;
return <h2>Radioactive Spiders for guest #{guest}</h2>;
}
export default function PeterParker() {
return (
<>
<Peter />
<Peter />
<Peter />
</>
);
}
Web image result

Example of pure component by passing a prop instead of modifying a pre-existing variable:

App.js

function Peter({ guest }) {
return <h2>Radioactive Spiders for guest #{guest}</h2>;
}

export default function PeterParker() {
return (
<>
<Peter guest={1} />
<Peter guest={2} />
<Peter guest={3} />
</>
);
}
Web image result

Using pure functions in your code isn’t just a best practice — it’s a strategy to make your codebase more robust and easier to manage. So next time you sit down to code, consider the purity of your functions and how they can simplify your application architecture!

Let’s conclude this by picturing the UI as a tree (after all, I’m a visual person and you may be too).

React also uses a tree to model the relationships between components and modules. This React render tree is the representation of the parent and child relationship between components:

Example of React render tree

Components located near the root of the tree are known as top-level components, while those without any children are called leaf components. This distinction helps in analyzing data flow and assessing rendering performance within the application.

Additionally, understanding how JavaScript modules relate to one another through a module dependency tree can provide valuable insights into your app’s structure. This model helps visualize the interdependencies between different modules.

An example module dependency tree

Build tools commonly use a dependency tree to package all the necessary JavaScript code for the client to download and run. When the bundled size becomes too large, it can negatively affect the user experience in React applications.

By understanding the module dependency tree, you can more effectively troubleshoot and resolve such issues.

Reference: react.dev and my lecture notes 😝💋


  • Implementing Dark Mode in React

    We have previously talked about useState before. A great way to create CSS classes on the fly is to use state variable! Here is an example of how to create Dark Mode in React by using string interpolation to construct the individual classes based on the state variable mode. index.html index.jsx App.jsx App.css So, if…

  • Understanding React’s useState Hook

    Buttons To use buttons, you can add the onClick event handler to handle clicks on the button. React also follows the camelCase unlike HTML/JavaScript; and to run the JavaScript, you add an embedded expression. App.jsx You can also run JavaScript directly inside the embedded expression. However, it is executed without clicking the button because the function is…

  • Understanding Props in React: A Comprehensive Guide

    This content explains the concept of props in React, which allow data to be passed to components, making them dynamic. It covers how to access props as objects, pass multiple properties, and handle different data types. The importance of correctly rendering non-string values and using props in JSX is emphasized.

  • The Power of JSX: Combining HTML and JavaScript

    JSX is a syntax extension for JavaScript that resembles HTML, used primarily in React to create components. It allows developers to write HTML-like code within JavaScript, enhancing readability and enabling dynamic web applications. With JSX, one can embed JavaScript expressions, making the integration of logic and UI layout seamless.

  • Organizing React Components for Better Code

    The content discusses best practices for organizing React components in separate files for maintainability. It details the process of importing React, creating functional components, and exporting them. Additionally, it covers returning multiple elements and using named vs. default exports, emphasizing strategic organization for better code management.

  • Step-by-Step Guide to Rendering React Components

    The content provides a step-by-step guide on rendering components in React. It emphasizes creating and linking HTML and JavaScript files, setting up the main component, and utilizing the createRoot function to manage rendering. The author injects humor while guiding readers through the essential concepts of React component rendering.

  • Introduction to React: Understanding the Basics

    React is a JavaScript library for creating single-page web applications that dynamically update without page reloads. It organizes code into reusable components, akin to functions returning HTML-like JSX. This enhances development efficiency, as components can be reused, resembling custom HTML tags. Overall, React simplifies coding while improving functionality.

  • HTML Structure Explained: A Beginner’s Guide

    The content discusses HTML, the foundational markup language for web development. It highlights its structure, including elements like tags and attributes. The post humorously reflects on the author’s learning journey while encouraging newbies by simplifying concepts like nesting elements and the importance of HTML in web design. It concludes with code examples.

  • Why Use Pure Functions in React Components?

    Pure functions in JavaScript are self-contained and produce consistent results without affecting external variables or objects. They enhance clarity and maintainability in code, minimizing bugs. Unlike impure components that modify existing variables, pure components receive data as props. Understanding component relationships, like the React render tree and module dependency tree, further optimizes performance and structure.

  • React Components Explained: A Guide for Developers

    This post analyzes React components, highlighting their crucial role in creating dynamic user interfaces. It details the types of components, including functional and class components, and explains props and state. Additionally, it covers lifecycle methods and emphasizes the importance of reusability and composition in building complex applications effectively.



Discover more from Steal My Notes

Subscribe to get the latest posts sent to your email.

Posted by

in

Discover more from Steal My Notes

Subscribe now to keep reading and get access to the full archive.

Continue reading