As lazy developers, we usually tend to use external resources to solve our problems. And when it comes to solving problems, utility libraries solve many of them. One of the most popular utility libraries out there is lodash.
Lodash is a JavaScript utility library. It provides a variety of functions for manipulating arrays, objects, strings, and numbers. (source: Lodash)
Since Lodash is written in Javascript, we can use it in any React application. Using Lodash in your React application is a simple and straightforward process.
To start using Lodash in React, you need to:
- Install Lodash by running
npm install lodash
- Import Lodash to your project by writing
import _ from lodash
Lodash helps to simplify your code and make your applications run faster. It does so by taking on some of the work that you’d normally have to do yourself. 🦥
tip
Lodash helps with all those little things that you don’t want to do over and over again like adding or removing properties from an object or adding or removing an element from a list.
What Is Lodash Used for in React
Lodash is built around four main ideas:
- Elegance
- Simplicity
- Consistency
- Performance
tip
If you want your codebase to have these qualities, you should consider adding Lodash to your React project.
Lodash provides functional programming helpers without extending any built-in objects. It includes the usual functional helpers, such as map
for applying a function to every element of an array, without cluttering up the global namespace.
It also has JSON iterators, which are amazingly useful for dealing with data coming from API endpoints.
note
This library is widely used in React projects because it provides an easy way to work with collections and arrays within React components. In the following examples, we'll showcase some of the problems that can be solved using Lodash.
Debouncing API Requests
Imagine we have an input field where the user can type anything. As the user is typing and input changes, we want to perform a search for a given keyword at the same time.
However, we don't want to perform a search every time user presses a button. It would lead to a lot of API requests and slow performance.
Luckily for us, this problem can be solved by using debounce
.
Input.jsx
import { useState, useCallback } from "react";
import debounce from "lodash/debounce";
const Input = () => {
const [inputValue, setInputValue] = useState("");
const sendQuery = (query) => {
// Call API with query parameter here
console.log(query);
};
// Delay search by 600ms
const delayedSearch = useCallback(
debounce((q) => sendQuery(q), 600),
[]
);
const handleChange = (event) => {
// Input will be changed immidiately
setInputValue(event.target.value);
// Search will only be called when user stops typing
delayedSearch(event.target.value);
};
return <input value={inputValue} onChange={handleChange} />;
};
export default Input;
Displaying Unique Values
Imagine we have an array with any values. But we only want to display unique values. Instead of writing a function that will find only unique values, we can just use the function from Lodash.
Users.jsx
import uniq from "lodash/uniq";
const users = ["Aaron", "John", "Mary", "John", "Angel", "Mary"];
const Users = () => {
return (
<div>
<strong>Unique names</strong>
<ul>
{uniq(users).map((user) => (
<li>{user}</li>
))}
</ul>
</div>
);
};
export default Users;
Using Lodash in React
In the previous section, we took a closer look at Lodash, and how it can be used to solve common problems in your React app. But we didn't entirely discuss its usage. 🦧
caution
If you're using Lodash in your React project, you need to know how to use it properly.
As we previously pointed out, the Lodash library contains a lot of helper functions. This makes the library very large in size. But in your React project, the chance of you using all of them is really small.
note
In real-life projects, we usually only import four or five functions.
Even if you import and use only one Lodash function, your project will download the whole Lodash library. This will cause your React app to grow in final size, and it'll eventually become slower. Especially for the users with poor internet connection.
Luckily for us, this problem can be solved by using one of the following methods.
Importing specific Lodash functions
When we download Lodash to our project, it downloads all the utility functions that it contains. However, this part is not making our application larger. The problem is when we write import _ from lodash
in any file.
By writing the given import statement, we're telling that we want to use the whole Lodash library. When in fact, we only want to use a specific function.
To import only a specific function, we can write our import statement in the following way.
import map from "lodash/map"
import forEach from "lodash/forEach"
This will prevent including the whole Lodash library in our final website. But instead, it will only include the functions that we specified.
Downloading specific Lodash functions
At the beginning of this article. We showed you the way of adding Lodash to your React project. It was by running npm install lodash
.
This command will download the whole Lodash library and add it to your project. However, there is another way to download only specific parts of the library.
tip
Each Lodash function has its own repository and can be installed separately.
Let's say we only need to use map
function. We can install it by running npm install lodash.map
. And then simply import it.
import map from "lodash.map"
The benefit of this method is its performance. Since it's much faster to download only one function instead of hundreds of them. The problem is when we need to use multiple functions, we have to install each of them separately.
Lodash Alternatives
Lodash is a great utility library, but it's not the only one. There are many projects out there, focusing on utility functions. In this section, we're gonna list a few of them. 💡
note
We're not suggesting these packages are better in any way than Lodash. We just believe that they're worth mentioning.
Ramda
There are already several excellent libraries with a functional flavor. Typically, they are meant to be general-purpose toolkits, suitable for working in multiple paradigms. Ramda has a more focused goal. Ramda is designed specifically for a functional programming style, one that makes it easy to create functional pipelines, one that never mutates user data. (source: Ramda)
MathJS
Math.js is an extensive math library for JavaScript and Node.js. It features a flexible expression parser with support for symbolic computation, comes with a large set of built-in functions and constants, and offers an integrated solution to work with different data types like numbers, big numbers, complex numbers, fractions, units, and matrices. (source: MathJS)
Lazy
Lazy.js is a functional utility library for JavaScript, similar to Underscore and Lodash, but with a lazy engine under the hood that strives to do as little work as possible while being as flexible as possible. (source: Lazy)
Concluding Thoughts
If you want to simplify your code, and at the same time make your application run faster, Lodash can help you with both. It also helps with annoying tasks you don’t want to do over and over.
In this article, we showed you how to install Lodash to your React project. And how to use Lodash in your React app. We also showed basic examples of using Lodash with React. And finally, we mentioned some of the Lodash alternatives.
With all this information in mind, it's time to take your project to another level, by installing a utility library of your choice. 🤘