开源日报每天推荐一个 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/