I've got a weekly newsletter where I share this type of content. It's not the link aggregator type, but it contains a brand new post & an old one I share
It's all about the frontend: JS/TS, React, DivOps, CSS & more! Subscribe to get your learn on ๐
I recently created a TypeScript generic utility type that recursively converted `Date` types into Firestore `Timestamp` types
The type was fun to come up w/ cuz I learned a lot but it's also a bit complex. Lemme break down all the TS features line by line...
/thread ๐งต๐๐พ
`ToFirestore<>` takes a single generic type param, `MaybeDate`. If it is a `Date` type, then the "true" branch of the type conditional returns a `Timestamp` type instead. This base case of the recursive type serves as the crux of the mapping of `Date` โก๏ธ `Timestamp` type
๐งต๐๐พ
The "false" branch of the outer conditional begins a nested one that converts `Date` โก๏ธ `Timestamp` types of an array type by recursively calling `ToFirestore<>` on the array item type
(the `infer` keyword auto-creates a new generic type that's the array items type)
What are some situations for when we can use the `useCallback()` & `useMemo()` Hooks in React components?
Well, one case where we need `useCallback()` is when we call a helper function w/in `useEffect()`, so we need "referential equality" to include it in deps
/thread ๐งต๐๐พ
I also use `useCallback()` by default when returning a function from a custom Hook cuz I dunno how that function will be used w/in host components
`useCallback()` gives a stable function reference similar to the updater func from `useState()` (the 2nd array element)
๐งต๐๐พ
The `useMemo()` Hook is similar to `useCallback()` except that it memoizes any value not just functions
So I use `useMemo()` in the same situations: when I have a derived object/array that's used in the deps of `useEffect()`
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!)