Home Web Front-end JS Tutorial Don't reinvent the wheel! Or utility libraries for Vue and React applications

Don't reinvent the wheel! Or utility libraries for Vue and React applications

Jul 17, 2024 pm 05:28 PM

Don’t reinvent the wheel! Or utility libraries for Vue and React applications

Introduction

Many developers, when it comes to standard web application functionality, for example: storing and managing boolean values, handling key pressed or creating stepper, often try to find how to do this or that function and more often they find a way to implement the functionality from scratch.

There’s no need in reinventing the wheel!

Creators and users of libraries of reusable functions for various frameworks (React, vue etc.) look at this approach with such a reaction.

For Vue — it is, for example, vueuse. (vue utility functions)

For React, the best one today is the brand new and actively supported reactuse (for react hooks)

What problem do these libraries solve?

They are needed to make life less challenging for developers. Prepare in advance all possible functions that developer may need in his work. If he will use a ready-made package, he will at least save his time, and at most minimize the probability of his error or bug found in the code, because each function is tested separately. The use case is actually huge. With the help of such libraries you can, for example:

  1. use web-sockets
  2. make queries
  3. detect user’s geolocation
  4. use localStorage
  5. easily create modal windows

And that’s just a small part of all the possible cases.

Why is VueUse cool?

VueUse is one of the most popular such libraries for vue. After all, it provides the most basic reusable functionality. Some people think that it is a standard when building Vue applications, and without it it is impossible to make it. It is hard to disagree, the library consists of more than two hundred functions and follows the ideology described above.

Best alternative for React

While praising vueuse as the best way to perfectly realize a great idea, we should not forget about the top 1 js library/framework — React. And here the situation was more unpleasent. After all, there is no established, reliable, extensive and the only library for React. There were some attempts from different developers, but in one of them there are too few hooks (in React they are hooks, yeah), somewhere there are hooks built using an unprocessed api.

To improve the situation, and as an alternative to vueuse, but in react, came reactuse.

Let’s take, for example, and try to create list management with the help of a library and using vanilla react only.

import { useList } from "@siberiacancode/reactuse";

function App() {
  const { value, set, push, removeAt, insertAt, updateAt, clear, reset } =
    useList(["Pink Floyd", "Led Zeppelin"]);
}
export default App;

We get value (array value), set (function to assign another array value), push (function to add values to the array), removeAt (delete by index), updateAt (change value by index), clear (clear the array), reset (reset to default value)
Now the code to get all these states and functions on vanilla react:

const [value, setValue] = useState<string[]>(["Pink Floyd", "Led Zeppelin"]);
  const [initialValue] = useState<string[]>(["Pink Floyd", "Led Zeppelin"]);
  const set = (newValue: string[]) => {
    setValue(newValue);
  };
  const push = (valueToPush: string) => {
    setValue((prevArray) => [...prevArray, valueToPush]);
  };
  const removeAt = (index: number) => {
    setValue((prevArray) => [
      ...prevArray.slice(0, index),
      ...prevArray.slice(index + 1),
    ]);
  };
  const insertAt = (index: number, item: "string") =>
    setValue((l) => [...l.slice(0, index), item, ...l.slice(index)]);

  const updateAt = (index: number, newValue: string) => {
    setValue((prevList) =>
      prevList.map((element, index) => (index === index ? newValue : element))
    );
  };

  const clear = () => setValue([]);
  const reset = () => setValue(initialValue);

And we get exactly the same methods and state. And the code is much more tiny and simpler

The library is actively maintained, new hooks are added, there is a convenient website with documentation, the hooks use simple sources and have a more elaborate API. Now there are more than 80 hooks implemented. I also want to note that there are absolutely new implementations, which I have not seen anywhere else:

  • usePaint — for creating canvas for drawing on it. You set the canvas, and the hook allows you to draw on it, adjust the size of the brush, color, opacity and the status “draw” or “now draw”
  • useStopwatch — for creating stopwatches
  • useEyeDropper — to use the dropper for color selection
  • huge amount of hooks fow working with user device or browser api (useMemory, useOperatingSystem, useClipboard, useBrowserLanguage, useHash and so on)

Conclusion

Such libraries should become a development standard, just because they allow you not to stay focused on the small details that were already invented a long time ago, you just need to import them in and use them.

reactuse links

npm — github

The above is the detailed content of Don't reinvent the wheel! Or utility libraries for Vue and React applications. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1510
276
Advanced JavaScript Scopes and Contexts Advanced JavaScript Scopes and Contexts Jul 24, 2025 am 12:42 AM

The scope of JavaScript determines the accessibility scope of variables, which are divided into global, function and block-level scope; the context determines the direction of this and depends on the function call method. 1. Scopes include global scope (accessible anywhere), function scope (only valid within the function), and block-level scope (let and const are valid within {}). 2. The execution context contains the variable object, scope chain and the values of this. This points to global or undefined in the ordinary function, the method call points to the call object, the constructor points to the new object, and can also be explicitly specified by call/apply/bind. 3. Closure refers to functions accessing and remembering external scope variables. They are often used for encapsulation and cache, but may cause

How to get the value of a selected radio button with JS? How to get the value of a selected radio button with JS? Jul 18, 2025 am 04:17 AM

There are two core methods to get the selected radio button value. 1. Use querySelector to directly obtain the selected item, and use the input[name="your-radio-name"]:checked selector to obtain the selected element and read its value attribute. It is suitable for modern browsers and has concise code; 2. Use document.getElementsByName to traverse and find the first checked radio through loop NodeList and get its value, which is suitable for scenarios that are compatible with old browsers or require manual control of the process; in addition, you need to pay attention to the spelling of the name attribute, handling unselected situations, and dynamic loading of content

Mastering JavaScript Concurrency Patterns: Web Workers vs. Java Threads Mastering JavaScript Concurrency Patterns: Web Workers vs. Java Threads Jul 25, 2025 am 04:31 AM

There is an essential difference between JavaScript's WebWorkers and JavaThreads in concurrent processing. 1. JavaScript adopts a single-thread model. WebWorkers is an independent thread provided by the browser. It is suitable for performing time-consuming tasks that do not block the UI, but cannot operate the DOM; 2. Java supports real multithreading from the language level, created through the Thread class, suitable for complex concurrent logic and server-side processing; 3. WebWorkers use postMessage() to communicate with the main thread, which is highly secure and isolated; Java threads can share memory, so synchronization issues need to be paid attention to; 4. WebWorkers are more suitable for front-end parallel computing, such as image processing, and

Vue 3 Composition API vs. Options API: A Detailed Comparison Vue 3 Composition API vs. Options API: A Detailed Comparison Jul 25, 2025 am 03:46 AM

CompositionAPI in Vue3 is more suitable for complex logic and type derivation, and OptionsAPI is suitable for simple scenarios and beginners; 1. OptionsAPI organizes code according to options such as data and methods, and has clear structure but complex components are fragmented; 2. CompositionAPI uses setup to concentrate related logic, which is conducive to maintenance and reuse; 3. CompositionAPI realizes conflict-free and parameterizable logical reuse through composable functions, which is better than mixin; 4. CompositionAPI has better support for TypeScript and more accurate type derivation; 5. There is no significant difference in the performance and packaging volume of the two; 6.

Exploring Type Coercion Rules in JavaScript Exploring Type Coercion Rules in JavaScript Jul 21, 2025 am 02:31 AM

Type casting is the behavior of automatically converting one type of value to another type in JavaScript. Common scenarios include: 1. When using operators, if one side is a string, the other side will also be converted to a string, such as '5' 5. The result is "55"; 2. In the Boolean context, non-Boolean values will be implicitly converted to Boolean types, such as empty strings, 0, null, undefined, etc., which are considered false; 3. Null participates in numerical operations and will be converted to 0, and undefined will be converted to NaN; 4. The problems caused by implicit conversion can be avoided through explicit conversion functions such as Number(), String(), and Boolean(). Mastering these rules helps

Advanced Debugging Techniques for Complex JavaScript Applications, utilizing Java Debugger Principles Advanced Debugging Techniques for Complex JavaScript Applications, utilizing Java Debugger Principles Jul 17, 2025 am 01:42 AM

Debugging complex JavaScript applications requires systematic use tools. 1. Set breakpoints and conditional breakpoints to intercept suspicious processes, such as before function entry, loop, asynchronous callback and filter according to conditions; 2. Enable Blackboxing function to block third-party library interference; 3. Use debugger statements to control debug entry based on environmental judgment; 4. Trace the call link through CallStack, analyze the execution path and variable status, thereby efficiently locate the root cause of the problem.

How to format a date in JS? How to format a date in JS? Jul 20, 2025 am 12:10 AM

Format dates in JavaScript can be implemented through native methods or third-party libraries. 1. Use native Date object stitching: Get the date part through getFullYear, getMonth, getDate and other methods, and manually splice it into YYYY-MM-DD and other formats, which is suitable for lightweight needs and does not rely on third-party libraries; 2. Use toLocaleDateString method: You can output such as MM/DD/YYYY format according to local habits, support multilingual, but the format may be inconsistent due to different environments; 3. Use third-party libraries such as day.js or date-fns: Provides concise syntax and rich functions, suitable for frequent operations or when extensibility is required, such as dayjs()

Building a CLI Tool with Node.js Building a CLI Tool with Node.js Jul 24, 2025 am 03:39 AM

Initialize the project and create package.json; 2. Create an entry script index.js with shebang; 3. Register commands through bin fields in package.json; 4. Use yargs and other libraries to parse command line parameters; 5. Use npmlink local test; 6. Add help, version and options to enhance the experience; 7. Optionally publish through npmpublish; 8. Optionally achieve automatic completion with yargs; finally create practical CLI tools through reasonable structure and user experience design, complete automation tasks or distribute widgets, and end with complete sentences.

See all articles