开源日报每天推荐一个 GitHub 优质开源项目和一篇精选英文科技或编程文章原文,坚持阅读《开源日报》,保持每日学习的好习惯。

2024年1月21日,开源日报第1081期:
今日推荐开源项目:《Bun》
今日推荐英文原文:《What is Ref and Ref Callback in React》


开源项目

今日推荐开源项目:《Bun》传送门:项目链接

推荐理由: Bun 是一个令人难以置信的快速JavaScript运行时、捆绑器、测试运行器和包管理器 - 一体化,其核心是Bun运行时,这是一个快速的JavaScript运行时,旨在作为Node.js的即插即用替代品,它由Zig编写,并由底层驱动JavaScriptCore,在启动时间和内存使用方面大大减少了消耗量

官网直达:bun.sh


英文原文

今日推荐英文原文:What is Ref and Ref Callback in React?

推荐理由:非常详细,Ref在React中是一个对象,用于引用React元素,手动操作DOM,通常用于添加动画、管理表单元素和第三方库,示例中使用useRef创建userNameRef,在组件挂载后将焦点设置在用户名输入框,而Ref Callback是另一种使用ref的方式,通过直接将函数传递给JSX元素的ref属性,回调函数接受HTMLElement作为参数,文中有更加细致的说明


What is Ref and Ref Callback in React?

Disclaimer: All the information below given are based on my experience and knowledge, it may have some mistakes and I’m not liable for any loss due to that. Please let me know if you have found out any mistakes in the comment section.

Hi there, I hope you have at-least basic knowledge in React JS.

What is Ref ?

In React ref is an object, which have reference to a React element, which is used to manipulate the DOM elements manually. Refs are most commonly used to add animations, managing values in form elements and in some third party libraries.

Before deep diving into ref, let’s see how a basic implementation in react looks like.

import {useRef, useEffect} from "react";

function App() {

  const userNameRef = useRef<HTMLInputElement>(null);

    useEffect(() => {
        if(userNameRef.current) {
            userNameRef.current.focus()
        }
    }, []);

  return (
    <div>
        <form>
            <div>
                <label htmlFor='username'>Username</label>
                <input ref={userNameRef} id='username' type='text'/>
            </div>
            <div>
                <label htmlFor='password'>Password</label>
                <input id='password' type='password'/>
            </div>
            <button>
                Submit
            </button>
        </form>
    </div>
  )
}

export default App

This React code defines a functional component named App representing a simple form with username and password inputs. The useRef hook creates a ref object named as userNameRef with initial value as null. Then we pass that userNameRef to ref prop of the username input element, which creates a reference to it.

The useEffect is triggered when the component mounts (empty dependency array []). It checks if userNameRef.current is not null (i.e., if the username input element exists), and if so, it sets the focus on that input element using userNameRef.current.focus() .

Ref Callback

There is an another way to use ref in React, that is using Ref Callback Funtion. Instead of using useRef() hook, we can directly pass a function to the ref prop of the JSX element, in which the function takes the HTMLElement as the parameter. So that we can access the element directly from the parameter inside the callback function. Usually this callback method of creating a ref is used where we often add or remove elements dynamically in React.

Note: This function will be called twice because, initally react assigns null to the ref element, then after mounting it will assigns the element to it. So there is no need of useEffect hook to execute the focus functionality.

Look at the code example below, it’s just the same logic that what we seen before on the top, but implemented using ref callback instead of using useRef hook.

function App() {

  function handleRef(element: HTMLInputElement) {
      if(element) {
          element.focus();    
      }
  }

  return (
    <div>
        <form>
            <div>
                <label htmlFor='username'>Username</label>
                <input ref={handleRef} id='username' type='text'/>
            </div>
            <div>
                <label htmlFor='password'>Password</label>
                <input id='password' type='password'/>
            </div>
            <button>
                Submit
            </button>
        </form>
    </div>
  )
}

export default App

Summary

Refs are very powerful tool in React, which enables us to easily attach animations, accessing values and triggering events etc just like we normally did in Plain JS.

Overuse of **refs** causes performance issues. So it is recommended to use state based controls over the elements.

Still it is encouraged to use ref for form elements, technically called as uncontrolled forms, which in contrast improves the performance of the application.

There is a library called React Hook Form, which is a great way for creating uncontrolled forms.


下载开源日报APP:https://openingsource.org/2579/
加入我们:https://openingsource.org/about/join/
关注我们:https://openingsource.org/about/love/