Skip to content
tinytip

Latest tips / 2

Custom hooks should return named tuples and not use "as const"

March 19, 2023
#react #typescript

When you create a custom hook in React that returns a tuple, like setState does, you must tell TypeScript that you are returning a tuple and not just an array of arbitrary length. For example, the following code will not work:

function usePromise<T>(fn: () => Promise<T>) {
// ...
return [value, isReady];
}

TypeScript will tell you that the return type of the hook is (T | boolean)[]. To make the return value type-safe, you can use as const:

function usePromise<T>(fn: () => Promise<T>) {
// ...
return [value, isReady] as const;
}

The return type is now readonly [T, boolean]. However, as a consumer of the hook you don't know what these values mean. What's that boolean value? Does it indicate if the promise is ready or if it failed? You can solve this by explicitly defining the return value and giving the tuple items a name:

function usePromise<T>(fn: () => Promise<T>): [value: T, isReady: boolean] {
// ...
return [value, isReady];
}

This way, the return type is [value: T, isReady: boolean] and the consumer of the hook knows what the values mean.

Find previous commands in the terminal

January 19, 2023
#terminal

When you want to rerun a previously executed command in the terminal, you can use the up and down arrow keys to navigate through the history of commands. If you want to search for a specific command, press Ctrl + R and start typing. The terminal will search through the history and show you the latest matching command. Press Ctrl + R again to search for older commands.

Create QR codes in Chrome to send URLs to your smartphone

January 19, 2023
#chrome

If you want to open a website on your smartphone, i.e. to test it on a mobile device, you can use the sharing feature of Chrome to create a QR code that you can scan with your smartphone. Click on the share icon in the address bar and select "Create QR Code". Then scan the QR code with the camera app of your smartphone to open the website.

Generate QR code in Chrome

Find the gitignore rule that excludes a file from git

October 27, 2022
#git

When a file is ignored by git you can use the check-ignore command which shows you why the file is ignored. This is useful if you have multiple .gitignore files or some complex patterns in your rules.

git check-ignore -v path/to/a/file.png

Empty Cache and Hard Reload in Chrome

October 27, 2022
#devtools #chrome

We all know cache invalidation is hard. If you experience some cache problems while working on a web project in Chrome you can empty the cache and do a hard reload. Just open the DevTools, right click (or long press) on the reload icon in the toolbar and choose "Empty Cache and Hard Reload":

Empty cache and Hard Reload in Chrome