Today I Learned
Get the RSS feed for Today I Learnedthreadreader
TIL about Threadreader
, a tool that helps you read Twitter threads way more easily. Oh sorry,
it’s not Twitter anymore, it’s X. Whatever, Elon.
Whatever the hell it’s called now, Threadreader
will unroll the tweet storm into a single,
cohesive, consumable chunk of content.
TIL about ts-reset
- it’s like CSS resets but for TypeScript! Shout out to Matt Pocock (and the team) for this!
Here’s an example of one of the rules:
import '@total-typescript/ts-reset/array-includes'
const users = ['matt', 'sofia', 'waqas'] as const
// .includes now takes a string as the first parameter
// BEFORE, it would have complained about the type of the first parameter
users.includes('bryan')
There are way more rules so I encourage you to give it a read and maybe incorporate it into your project!
Show your react router routes
TIL that you can utilize npx react-router routes
to see all the routes in your app!
For my site, here’s what I get:
<Routes>
<Route file="root.tsx">
<Route path="newsletter/rss.xml" file="routes/_extras.newsletter.rss[.xml].tsx" />
<Route path="action/old-refresh-cache" file="routes/action.old-refresh-cache.tsx" />
<Route path="blog/rss.xml" file="routes/_extras.blog.rss[.xml].tsx" />
<Route path="til/rss.xml" file="routes/_extras.til.rss[.xml].tsx" />
<Route path="action/theme-switcher" file="routes/action.theme-switcher.tsx" />
<Route path="action/refresh-cache" file="routes/action.refresh-cache.tsx" />
<Route path="action/newsletter" file="routes/action.newsletter.tsx" />
<Route path="blog" index file="routes/blog._index/route.tsx" />
<Route path="tags" index file="routes/tags._index.tsx" />
<Route path="blog/:slug" file="routes/blog.$slug/route.tsx" />
<Route path="tags/:slug" file="routes/tags.$slug.tsx" />
<Route path="inngest" file="routes/inngest.ts" />
<Route index file="routes/_index.tsx" />
<Route path="health" file="routes/health.tsx" />
<Route path=":page" file="routes/$page.tsx" />
<Route path="about" file="routes/about/route.tsx" />
<Route path="til" file="routes/til/route.tsx" />
<Route path="*" file="routes/$.tsx" />
</Route>
</Routes>
headless ui
TIL about headless ui - a library from tailwindlabs
that gives you access to
unstyled ui components that integrate beautifully with tailwind
. If you’re wondering how I found out
about this, Wapplyzer revelead it to me 😆!
c15t (consent management)
TIL about c15t, a new consent management framework with some awesome React support! You can even self-host it (which is a major win for nerds like me)
RBAC in JS
TIL about a role based access control (RBAC) library in JavaScript. CASL
is a library that allows us to declaratively restrict access to resources based on roles and permissions.
import { createContext } from 'react'
import { createContextualCan } from '@casl/react'
export const AbilityContext = createContext()
export const Can = createContextualCan(AbilityContext.Consumer)
export default () => {
const createTodo = () => {
/* logic to show new todo form */
}
const ability = useContext(AbilityContext)
return (
<div>
{ability.can('create', 'Todo') && (
<button onClick={createTodo}>Create Todo</button>
)}
</div>
)
}
easy stacking in css
TIL, it’s pretty easy to stack elements in CSS, without having to use positioning! It’s a litle bit more verbose to do it in tailwind, but it’s the same idea.
.parent {
display: grid;
}
.child {
grid-area 1 / 1
}
Top Card
This card is on top... hover me!
rss feed generator
TIL about feed
, an npm package that allows you to quickly generate an RSS feed for your website!
I used it to generate an RSS feed for my blog and my TIL feeds! It’s pretty simple and super easy to plug into your existing project.
coolors.co
TIL about coolors.co
— a superfast color palette generator. If you’re anything like me,
you’ll probably use it whenever you need to generate a color palette for your side projects, you know,
those side projects that you’re totally working on and not abandoning for a while.
Optional chaining
I learned this hard lesson today. Optional chaining is for uncertain values — not uncertain existence.
If I’m not sure if a global object exists, I can’t rely on optional chaining to access it. I have to check for existence first.
// 👇 this is a valid expression in node
// we check to see if window exists
if (typeof window !== 'undefined') {
window.localStorage.setItem('key', 'value')
}
// 👇 this is not a valid expression in node
// window is undefined (its existence is uncertain)
window?.localStorage.setItem('key', 'value')
Node Modules Inspector
TIL about the node-modules-inspector
— a package that allows you to visualize your node_modules folder,
inspect your dependencies, and so much more 🤯! I’m a big fan of the visualizations, since I’m more of a
visual kinda person. You can use it in your own project with this simple command: npx node-modules-inspector
.
Typescript Ported To Go
TypeScript’s compiler is being reimagined. Currently at version 5.8, TypeScript is still written in TypeScript itself, but there are plans to port it to Go for version 7.
This change promises to improve compilation times—by up to 10 times faster! True, the speed boost
is something we probably won’t see for a few months or years, but I’m super excited to see Go
get some much needed love and attention, since you know, it’s my secondary language of choice.
Better Sleep
TIL about Magnesium Glycinate
, a supplement that helps promote better sleep! I’ve been having a tough time
falling asleep lately, especially after a tough Brazilian Jiu Jitsu practice, or an intense workout. One of my
friends recommended Magnesium Glycinate
as a way to help me sleep better. Let’s see how it works… I just ordered
some today 😆!
Fontsource
TIL about Fontsource
, a free Vercel resource that provides you with information on how to easily
install and self-host
web fonts. They support all Google Fonts, as well as open source ones!
Tanstack Form
TIL: Tanner Linsley, the creator of TanStack Query, Router, and Start, just dropped TanStack Form!
True to form, it’s framework-agnostic, headless, and has zero dependencies. It also handles deeply nested objects out of the box, making it a powerful alternative to traditional form libraries.
System Font Stack
TIL about a growing movement on the web where people are choosing to use system fonts instead of loading custom fonts. Over the years, the default system fonts included with operating systems have become quite robust and visually appealing. If you’re concerned about performance or don’t require a fancy web font, this could be a great solution for you.
Data attribute state management
This one’s pretty sweet and I’ve been reaching for it a lot lately at work!
Rather than having multiple className
conditions, you can use a
data-attribute
to manage your state.
This is not only a great way to keep your component clean but also allows you
to target any state pertinent to your component without JavaScript! Mind you,
I’m assuming you’re using something like Tailwind
for your styling.
// no reliance on utility functions like `twMerge`
<div
data-state-can-scroll={canScroll}
className="data-[state-can-scroll=false]:hidden"
>
Hidden when canScroll is false!
</div>
web extension framework
TIL about wxt! It’s like Nuxt but for web extensions.
TIL about a local first tool for image compression called sqoosh
. No more
sending images to random servers just to compress them! 😆.
TIL about bolt.new
, an AI-powered web agent that lets you deploy apps via
Stackblitz. It’s a pretty sick way to throw up a demo of a new app to illustrate
a concept.
CSS tidbits
TIL about the following…
/* top, left, right, button, are all set to to the same value */
.box {
inset: 0;
}
- The
inset
property is a shorthand fortop
,right
,bottom
, andleft
properties. - Absolute elements can only be contained by other elements using Positioned layout.
- Positioned elements will always render on top of non-positioned ones
- Stacking context
is the stacking order of elements that are positioned.
- We can create a stacking context by combining a non-static position with a
z-index. So position
absolute
andz-index
will create a stacking context. - We can also create one by setting opacity to less than 1.
- Check out the link above for more info.
- We can create a stacking context by combining a non-static position with a
z-index. So position
- The
isolation
property allows you to create a stacking context. We can add this to a parent element and then we can forget about having to add aposition: relative
andz-index
to the children. It is the lightest weight way to create a stacking context. - The
z-index
property can be used in a flexbox the same way as it can be used with a positioned element.
CSS stacking context inspector
TIL about the stacking context inspector. It’s a tool that allows you to inspect the stacking context of an element.
Leave.Comments.
More of a public service announcement and a reminder to myself (especially for
my personal projects), to leave comments on any funky things you’re doing in
code. I wasted an hour battling a bug in my blog because I didn’t leave a
comment regarding a @ts-ignore
directive.
Leave. Comments. Please.
reach.tech
Kent showed me a great way to have a stable id for my react components, between server and client renders.
Ideally, you would be reaching for useId
from react
but if you’re using an
older version of react, like 17
or 16
, then you can use auto-id
from
reach.tech
instead.
Til about zoxide
which is a faster and more robust cd
alternative; it lets
you navigate your filesystem faster and more reliably.
z ~/Documents/new-blog
z ~/Documents/rehype-code-titles
# Go back to the last directory (new-blog)
z -
# Go to the `new-blog` directory
z rehype-code-titles
# Go back to your home directory
z
# open a fzf menu of possible entries that begin with `re`
zi re<SPACE><TAB>
Standard Schema
TIL about the Standard Schema! It’s an effort to standardize the interface of TypeScript validation libraries.
To pull directly from the docs, The goal is to make it easier for ecosystem tools to accept user-defined type validators, without needing to write custom logic or adapters for each supported library.
editing the whole document
TIL that you can edit the whole document with document.designMode = 'on'
!
Toggle document.designMode
happiness one liner
Happiness = results - expecations-unknown
array with method
Today I learned about the with
method on the Array.prototype
object. This
method is used to create a shallow copy of an array but with one element
replaced at a given index.
const arr = [1, 2, 3]
const newArr = arr.with(0, 5)
console.log(arr) // [1, 2, 3]
console.log(newArr) // [5, 2, 3]
This is useful when you want to replace elements in an array without mutating the original array.
So it’s even easier now to add a documentation website to your project! While
looking over the Zod
github repo, I saw that they were using docsify
to
house their documentation. It’s pretty slick and I intend to use it for my own
projects… well at least the work ones 😆.
react-error-boundary
If you’re not using a meta framework like Next.js or Remix, I’d high suggest you check out react-error-boundary.
Seriously, Taran, use this at work.
TS satisfies without satsify
TIL about how one can use satisfies
in typescript, without satisfy
at all!
// taken right from Kent's blog
type OperationFn = (left: number, right: number) => number
// this is a restriction on the operations object
// but with satisfies, I leave myself room to add more operations and don't need to manage another type
const operations = {
'+': (left, right) => left + right,
'-': (left, right) => left - right,
'*': (left, right) => left * right,
'/': (left, right) => left / right,
} satisfies Record<string, OperationFn>
arethetypeswrong
TIL there’s a tool that can help you find out if your types are wrong for your library!
Til about raycast! The productivity tool that our macs should have shipped with ❤️
choose your license
Struggling to choose the right license for your project? There’s a great tool for that!
TIL about wave app! I’m using it to track my expenses and the invoices for my company! It’s pretty cool.
Better node objects logging!
Sick of seeing truncated Objects
in Node? I got you bro (well Matt Pocock has
got you).
let deepNesting = {
level1: {
level2: {
level3: {
level4: {
level5: {
name: 'Moderately Nested Object',
value: 42,
attributes: {
created: '2023-10-01',
modified: '2023-10-15',
tags: ['demo', 'test', 'nested'],
metadata: {
author: 'Jane Doe',
version: '1.0',
license: 'MIT',
},
},
items: [
{
id: 1,
description: 'First item',
status: 'active',
},
{
id: 2,
description: 'Second item',
status: 'inactive',
},
],
},
},
},
},
},
}
// logs: { level1: { level2: { level3: [Object] } } }
console.log(deepNesting)
// You get the whole object!
console.dir(deepNesting, { depth: Infinity })
Matt is the man!
bulletproof react
TIL there’s a useful github repo for bulletproof react!
It gives you a bunch of useufl tips and explanantions on how to make your react code bulletproof.
colored console log
TIL that you can use console.log
with color!
console.log(
'This is %cMy stylish message',
'color: yellow; font-style: italic; background-color: blue;padding: 2px',
)
changesets
Need a tool to help you manage your versioning and changelogs? Check out changesets!
Multiple Neovim Configs
Today I learned how to create multiple Neovim Configs. I’ve set up a home and work config respectively.
git recent
TIL about git recent
by Paul Irish. It’s a command that shows you your latest
local git branches! Super useful when you’re at work and got a lot of stuff on
the go.
git recent
# example output
:'
* main 7167899 (19 hours ago) Taranveer Bains
new til
feature/partytown 548eaf3 (2 days ago) Taranveer Bains
chore(dev-server): update dev script
'
interpolation
Interpolation is defined as “the insertion of something of a different nature into something else.”
css-color-filter-generator
TIL that there’s a tool to help you apply color filters to your dom nodes!
Storybook ArgeTypes
TIL that Storybook has a way to specify the behavior of args
— ArgeTypes
.
This is a great way to constrain the values that your component can accept and
provides information about args
that aren’t explicitly set in the story.
// Replace your-renderer with the renderer you are using (e.g., react, vue3, angular, etc.)
import type { Preview } from '@storybook/your-renderer'
const preview: Preview = {
argTypes: {
// 👇 All stories expect a label arg
label: {
control: 'text',
description: 'Overwritten description',
},
},
}
export default preview
stay away
Keep away from people who try to belittle your ambitions. Small people always do that, but the really great make you feel that you, too, can become great.
-Mark Twain
Ecosystem Performance
TIL about e18e (Ecosystem Performance). It’s an initiative to connect folks and projects working on improving JS package performance.
deepClone... nah, structuredClone
TIL that if we want to make a deepClone
of an object in JS, there’s a built in
method in most browsers: structuredClone
!
The old one (which works but doesn’t account for things like Set
and Map
or
even Date
)
const originalObject = {
name: "John",
age: 30,
date: new Date(),
details: {
hobbies: ["reading", "gaming"],
address: {
city: "New York",
zip: "10001",
},
},
};
const clonedObjectOldWay = JSON.parse(JSON.stringify(originalObject));
// what do you think happened to the date? 😏
// hint... no longer a string!
console.log(clonedObjectOldWay);
console.log(originalObject.date instanceof Date); // true
console.log(clonedObjectOldWay.date instanceof Date); // false (Date is not preserved)
Shout out to Matt Pocock — the person behind Total Typescript — for the twitter thread that exposed me to this function!
do what matters
Don’t forget this brother. My guy hit me hard with this; it was too damn early in the morning for them ninjas to be chopping onions 🥲!
Do what matters with who matters, while it matters.
-Mark Techson
margin vs padding
TIL margin
is meant to increase the distance between siblings. It is not
meant to increase the gap between a child and its parent’s bounding box; that’s
what padding
is for.
css height and width tidbit
width
looks up the tree but height
looks down the tree. An element’s width
is calculated based on its parent’s size, but an element’s height is calculated
based on its children.
Thanks Josh Comeau!
css list of mistakes
😆 while going through a CSS workshop, I came across this list of CSS mistakes. Be humble folks. We all mistakes.
css inheritable
Here’s a list (probably not complete) set of inheritable css properties.
observables api
TIL, from Dom Farolino that he’s trying to make addEventListener
extinct with
the observables api!
// Filtering and mapping:
element
.on('click')
.filter((e) => e.target.matches('.foo'))
.map((e) => ({ x: e.clientX, y: e.clientY }))
.subscribe({ next: handleClickAtPoint })
react internals explorer
Check out this dope tool for understanding the React internals! So dope!
Anger and happiness
Never make a decision in anger, and never make a promise in happiness
-Imam Ali Ibn Abi Talib
Better prose editing
TIL about an app that’ll edit your prose for you! Hemingway App should be able to help me write with better clarity and conciseness. I’m a wordy son of a gun.
patch-package
Got a node_module
giving you a headache? Need to give it a band-aid? Thank
your lucky stars for
patch-package.
It’s a vital band-aid for the bleeding edge!