The .reduce() method is maybe the most powerful, yet least understood array method. It basically allows us to transform an array into... nearly anything else
Let's re-implement 1️⃣0️⃣ lodash functions to learn more about how for examples on how .reduce works
/thread 👇🏾🧵
1️⃣ sum()
ℹ️ Computes the sum of the values in an array
The function is called a "reducer" & the 2nd param is our initial value
The 1st arg of the reducer is the "accumulator" (the value we're building up). The 2nd is the current array element in the iteration
/thread 👇🏾🧵
2️⃣ countBy()
ℹ️ Creates an object w/ keys that are the array elements and values that are their counts
Here we're turning an array into an object
(can't forget to return the object we're accumulating!)
/thread 👇🏾🧵
3️⃣ flatten()
ℹ️ Flattens the array a single level deep (also available as .flat() since ES2019)
Here we go from an array to a new (& flattened) array. A "flatDeep()" would need to be recursive
/thread 👇🏾🧵
4️⃣ filter()
ℹ️ Iterates over the array, returning a new one containing the elements that pass the test implemented in the "predicate" function
Of course .filter() already exists on arrays, but this shows how it can implement one of the *main* array utility methods
/thread 👇🏾🧵
5️⃣ fromPairs()
ℹ️ Returns an object composed from key-value tuple pairs (equivalent to `Object.fromEntries()`added in ES2019)
/thread 👇🏾🧵
6️⃣ keyBy()
ℹ️ Creates an object lookup using the property name as the lookup key
/thread 👇🏾🧵
7️⃣ map()
ℹ️ Creates a new array of values populated w/ the result of calling the mapper function on every element in the array (already exists of course as .map())
Shout out to the exponentiation (**) operator (ES2016) which is shortcut syntax for `Math.pow`
/thread 👇🏾🧵
8️⃣ max()
ℹ️ Computes the maximum value w/in the array
(FYI - we can actually use the spread operator w/ `Math.max` to implement this with far less code 🤯)
/thread 👇🏾🧵
9️⃣ some()
ℹ️ Tests whether at least one element in the array passes the test implemented by the "predicate" function (exists as .some() on arrays)
This shows reducing an array to a boolean. But is sub-optimal because it doesn't short-circuit like .some() does
/thread 👇🏾🧵
1️⃣0️⃣ zip()
ℹ️ Creates an array of grouped elements by index
Here we get to use the 3rd arg of the reduce function, which is the value's index w/in the array
/thread 👇🏾🧵
How do you feel about .reduce()? It took me a while, but once I got the hang of it, it leveled up my JS data transformation skills
Feel free to check out my latest post on re-implementing lodash functions w/ .reduce() for more info
If you love JavaScript like I do and wanna learn more about it (like I do), you should subscribe to the BenMVP Newsletter. Every week I share something new about JS, TS, React, DivOps, or all of them combined!
Here is a quick React custom Hook that supports copying text to the system clipboard. It also returns a copied/failed status that can be reflected in the UI
(I remember the days when we could only do this w/ Flash 😭)
more details in the thread 🧵👇🏾
useCopyToClipboard returns a copy function that the UI calls when the user wants to copy the text (likely a button click). It updates the status based on the success/failure of writing to the clipboard
It uses useCallback to ensure a stable function reference
🧵👇🏾
It also uses useEffect to set a timeout that will reset the status after a specified amount of time. This basically makes the status fleeting, which is a typical user experience
Using objects/arrays in deps for React useEffect can cause it to run the effect on *every* re-render even if contents are the same cuz the references are different
We've got a couple of options...
1️⃣ Depend on the obj properties instead of the entire obj
/thread 🧵👇🏾
2️⃣ Duplicate the object within the effect when the *entire* object is needed. useEffect then depends on the pieces needed to create the object
In general creating object literals is cheap so the perf wins from optimized useEffect should outweigh the duplication
🧵👇🏾
3️⃣ Memoize/cache the object w/ useMemo Hook if creating the object is too expensive to do it twice. The obj is now safe to use in deps
This is suggested by the `react-hooks/exhaustive-deps` ESLint rule (part of `eslint-plugin-react-hooks` which you should totally be using)
I used to tell folks learning React to learn JS really well first. I had good intentions but was still gate-keeping 😔
But I do think knowing modern JS can really level-up your React skills and I've got top 10 features I think will help you be more awesome-r 🔥🔥
[🧵 thread]
1. ES Modules
I see lots of confusion about when to use named vs default imports. The import style depends on how it was exported (named or default)
Named imports go within the curly braces & the single default import is outside of them 🤓
2. Arrow functions
Arrow functions can exist everywhere within your React app. Some folks (like myself) replace all functions with arrows while others only use them in spots
They really win w/ character savings but for those unfamiliar w/ the syntax they can lose w/ clarity 🧐