Today I learn

Here you can find what I have learned as I go about my day.

20/02/2025

go

Defer vs EOF calls in Go

Key Differences:

  1. Execution Order
func deferExample() {
    defer fmt.Println("1")
    defer fmt.Println("2")
    defer fmt.Println("3")
}
// Output: 3, 2, 1 (LIFO - Last In First Out)
 
func normalExample() {
    fmt.Println("1")
    fmt.Println("2")
    fmt.Println("3")
}
// Output: 1, 2, 3 (Sequential)
  1. Error Handling
func withDefer() {
    f, err := os.Open("file.txt")
    if err != nil {
        return // file will never be closed
    }
    defer f.Close() // guaranteed to run even if error occurs later
    // ... work with file
}
 
func withoutDefer() {
    f, err := os.Open("file.txt")
    if err != nil {
        return // file will never be closed
    }
    // ... work with file
    f.Close() // might not be reached if panic or early return occurs
}
  1. Early Returns
func withDefer(x int) {
    defer fmt.Println("cleanup")
    if x < 0 {
        return // cleanup still runs
    }
    // ... more code
}
 
func withoutDefer(x int) {
    if x < 0 {
        fmt.Println("cleanup")
        return // need to duplicate cleanup code
    }
    // ... more code
    fmt.Println("cleanup")
}

Key advantages of defer:

  • Guaranteed execution (even during panics)
  • Cleanup code stays close to resource acquisition
  • Handles multiple return points elegantly
  • Perfect for cleanup operations (closing files, mutexes, etc.)

When to use each:

  • Use defer for cleanup operations and guaranteed execution
  • Use end-of-function calls for sequential operations where order matters
"Edgey casey!"

20/02/2025

react

How SSR Works in React

Server-Side Rendering (SSR) is when React components are rendered to HTML on the server before being sent to the client. Here's the flow:

  1. Server Receives Request

    • User requests a page
    • Server runs React code
  2. Server Renders React

    • React components are rendered to HTML strings
    • Initial state is serialized
    // Example server code
    const html = ReactDOMServer.renderToString(<App />)
    const state = JSON.stringify(initialState)
  3. Server Sends Response

    • HTML is sent to browser
    • Initial state is included in a script tag
    • React client bundle is included
  4. Client Hydration

    • Browser loads React
    • React "hydrates" the HTML by attaching event listeners
    • App becomes interactive without re-rendering

Benefits:

  • Faster initial page load
  • Better SEO (search engines see complete HTML)
  • Better performance on slow devices

This is called "isomorphic" or "universal" rendering because the same React code runs on both server and client.

"No way..."

20/02/2025

javascript

Javascript Asynchronous Precendence.

What would the output of the following function be?

function main() {
  setTimeout(() => console.log(3), 0)
 
  new Promise((resolve) => resolve(2)).then((val) => console.log(val))
 
  console.log(1)
}

console.log(1) runs first, Promise goes second and lastly setTimeout. This is because JavaScript has different types of queues for handling asynchronous operations:

  1. Call Stack: Executes synchronous code immediately (console.log(1))
  2. Microtask Queue: Handles Promises and process.nextTick(), has higher priority
  3. Macrotask Queue: Handles setTimeout, setInterval, and I/O operations

Even though both setTimeout and Promise are asynchronous operations, Promises are processed in the microtask queue which is processed immediately after the call stack is empty, while setTimeout callbacks go into the macrotask queue which is processed later.

This execution order is part of the JavaScript Event Loop:

  1. Execute all synchronous code
  2. Process all microtasks (Promises)
  3. Process one macrotask (setTimeout)
  4. Repeat steps 2-3

So the output will be:

1
2
3
"Deep..."

08/01/2025

env

useMemo & useCallback skips re-render

Example Google service account JSON:

{
  "type": "service_account",
  "project_id": "test_project",
  "private_key_id": "abc123",
  "private_key": "-----BEGIN PRIVATE KEY-----\nblahblah\n-----END PRIVATE KEY-----\n",
  "client_email": "api@test_project.iam.gserviceaccount.com",
  "client_id": "107309273795607181234",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/api%40test_project.iam.gserviceaccount.com",
  "universe_domain": "googleapis.com"
}

Encode the file to base64. Base64 Encoder

Place the base64 string as an environment variable

GSA_BASE64="ewogICJ0eXBlIjogInNlcnZpY2VfYWNjb3VudCIsCiAgInByb2plY3RfaWQiOiAidGVzdF9wcm9qZWN0IiwKICAicHJpdmF0ZV9rZXlfaWQiOiAiYWJjMTIzIiwKICAicHJpdmF0ZV9rZXkiOiAiLS0tLS1CRUdJTiBQUklWQVRFIEtFWS0tLS0tXG5ibGFoYmxhaFxuLS0tLS1FTkQgUFJJVkFURSBLRVktLS0tLVxuIiwKICAiY2xpZW50X2VtYWlsIjogImFwaUB0ZXN0X3Byb2plY3QuaWFtLmdzZXJ2aWNlYWNjb3VudC5jb20iLAogICJjbGllbnRfaWQiOiAiMTA3MzA5MjczNzk1NjA3MTgxMjM0IiwKICAiYXV0aF91cmkiOiAiaHR0cHM6Ly9hY2NvdW50cy5nb29nbGUuY29tL28vb2F1dGgyL2F1dGgiLAogICJ0b2tlbl91cmkiOiAiaHR0cHM6Ly9vYXV0aDIuZ29vZ2xlYXBpcy5jb20vdG9rZW4iLAogICJhdXRoX3Byb3ZpZGVyX3g1MDlfY2VydF91cmwiOiAiaHR0cHM6Ly93d3cuZ29vZ2xlYXBpcy5jb20vb2F1dGgyL3YxL2NlcnRzIiwKICAiY2xpZW50X3g1MDlfY2VydF91cmwiOiAiaHR0cHM6Ly93d3cuZ29vZ2xlYXBpcy5jb20vcm9ib3QvdjEvbWV0YWRhdGEveDUwOS9hcGklNDB0ZXN0X3Byb2plY3QuaWFtLmdzZXJ2aWNlYWNjb3VudC5jb20iLAogICJ1bml2ZXJzZV9kb21haW4iOiAiZ29vZ2xlYXBpcy5jb20iCn0="

Decode and parse the JSON when asked for credential

const credentials = JSON.parse(
  Buffer.from(process.env.GSA_BASE64, "base64").toString("utf-8")
)
 
// Google Sheets API setup
const auth = new google.auth.GoogleAuth({
  credentials,
  scopes: ["https://www.googleapis.com/auth/spreadsheets"]
})
"Useful for long/json values"

07/12/2024

typescript
react

useMemo & useCallback skips re-render

The useMemo and useCallback hooks in React help optimize performance by preventing unnecessary re-renders. useMemo memoizes the result of a computation, ensuring the value is only recalculated when its dependencies change. useCallback memoizes a function reference, preventing child components from re-rendering when the function is passed as a prop unless its dependencies change. Together, they help minimize redundant rendering, especially in components with heavy computations or deep prop trees.

"Use only when necessary"

22/10/2024

git

What happens when rebasing.

When rebasing MyBranch onto master, "incoming" refers to MyBranch (the branch being replayed), and "current" is master. Rebase resets MyBranch to master, replays its commits, and temporarily considers master as "current." After rebasing, MyBranch becomes "current" again. This differs from merging, where "incoming" is the branch being merged, and "current" remains your branch.

"Good for solo MR, sort of bad with team without communication"