開源日報每天推薦一個 GitHub 優質開源項目和一篇精選英文科技或編程文章原文,堅持閱讀《開源日報》,保持每日學習的好習慣。

2024年1月12日,開源日報第1072期:
今日推薦開源項目:《meshery》
今日推薦英文原文:《How I Have Mastered Closures in React 🚀》


開源項目

今日推薦開源項目:《meshery》傳送門:項目鏈接

推薦理由:Meshery是一個自助工程平台,是開源的、雲原生的管理器,可以實現基於K8s的所有基礎設施和應用程序的設計和管理。除了其他功能外,作為一個可擴展的平台,Meshery提供了可視化和協作式GitOps,在管理K8s多集群部署時擺脫了YAML文件的束縛


英文原文

今日推薦英文原文:How I Have Mastered Closures in React 🚀

推薦理由:文章解釋了JavaScript中閉包的概念,通過示例說明展示了一種更清晰、更模塊化處理狀態邏輯的方法,也強調的好處包括封裝、私有作用域、更清晰的代碼以及減少全局作用域污染


How I Have Mastered Closures in React 🚀

React, a powerful and widely-used JavaScript library for building user interfaces, offers developers a flexible and efficient way to create interactive web applications. One of the key concepts in React that can greatly enhance your programming skills is the use of closures. In this article, we』ll explore how closures work and how I have leveraged them to write cleaner and more maintainable React code.

Understanding Closures in JavaScript

Before diving into React-specific examples, let』s ensure we have a solid understanding of closures in JavaScript. A closure is formed when a function is defined inside another function, allowing the inner function to access the outer function』s variables and parameters. This encapsulation of variables creates a private scope for the inner function, even after the outer function has finished executing.

function outerFunction() {
  let outerVariable = 'I am from the outer function';

  function innerFunction() {
    console.log(outerVariable);
  }

  return innerFunction;
}

const closureExample = outerFunction();
closureExample(); // Output: "I am from the outer function"

In the example above, innerFunction forms a closure by referencing outerVariable, even though the outer function outerFunction has completed execution. This ability to "remember" variables from the outer scope is crucial for various programming scenarios.

Applying Closures in React Components

Now, let』s see how closures can be applied in the context of React components. Consider a common scenario where you want to create a reusable component that handles state logic internally.

import React, { useState } from 'react';

const Counter = () => {
  // State is declared inside the component
  const [count, setCount] = useState(0);

  const increment = () => {
    setCount(count + 1);
  };

  const decrement = () => {
    setCount(count - 1);
  };

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
      <button onClick={decrement}>Decrement</button>
    </div>
  );
};

In this example, the state (count) and the state updater function (setCount) are declared using the useState hook. The increment and decrement functions use these state-related variables. However, what if you want to encapsulate the state logic and provide an external function to handle the state updates?

This is where closures come into play:

import React from 'react';

const Counter = () => {
  // State is declared inside the closure
  const createCounter = () => {
    let count = 0;

    const increment = () => {
      count += 1;
      console.log('Incremented! Current count:', count);
    };

    const decrement = () => {
      count -= 1;
      console.log('Decremented! Current count:', count);
    };

    const getCount = () => count;

    return { increment, decrement, getCount };
  };

  const counterInstance = createCounter();

  return (
    <div>
      <p>Count: {counterInstance.getCount()}</p>
      <button onClick={counterInstance.increment}>Increment</button>
      <button onClick={counterInstance.decrement}>Decrement</button>
    </div>
  );
};

In this example, the createCounter function serves as a closure, encapsulating the state (count) and state manipulation functions (increment and decrement). The returned object from createCounter provides access to the internal state and functions, creating a more modular and reusable component.

Benefits of Using Closures in React

  1. Encapsulation and Modularity: Closures allow you to encapsulate state and behavior within a component, promoting a modular and reusable code structure.
  2. Private Scoping: The variables inside the closure are not accessible from outside, providing a level of privacy and preventing unintended manipulation.
  3. Cleaner Code: By encapsulating logic within closures, your component code becomes cleaner and more focused, making it easier to understand and maintain.
  4. Reduced Global Scope Pollution: Closures help in minimizing the use of global variables, reducing the risk of naming conflicts and unintended side effects.

In conclusion, mastering closures in React can significantly enhance your ability to write efficient and maintainable code. By understanding how closures work and applying them judiciously, you can create more module.


下載開源日報APP:https://openingsource.org/2579/
加入我們:https://openingsource.org/about/join/
關注我們:https://openingsource.org/about/love/