Next.Js using Context to pass data between components and avoid props drilling

'use client'
import { createContext, useContext, useState } from 'react';
 
export const MyContext = createContext();
 
export function MyProvider({children}) {
const [mymessage, setMymessage] = useState("");
 
return (
    <MyContext.Provider value={{ mymessage, setMymessage }}>
        {children}
    </MyContext.Provider>
    )
}
 
export function useMy() {
    const context = useContext(MyContext)
    if (!context) {
        throw new Error('useTheme must be used within ThemeProvider')
    }
    return context;
}

Usage:

components/Navbar.js

 
const { mymessage } = useMy();
 
console.info(mymessage);

page.tsx

 
const { setMymessage } = useMy();
 
setMymessage('message fror Navbar');

Dictionary of online marketing

PLA – Product Listing Ad – A commercing ad in Google, Bing to show individual product with images. On click it takes to PDP page with that ad
PPC – Pay per click – advertisers pay a fee each time a user clicks on their ad

Asyncronously execute shell script from node.js app

const exec = require('child_process').exec
var yourExecCmd = 'ls -ltr'
 
// Function to exec shell cmd with callback
function execWithCallback() {
    this.execCommand = function(cmd, callback) {
        exec(cmd, (error, stdout, stderr) =&gt; {
            if (error) {
                console.error(`exec error: ${error}`)
                return
            }
            console.log('stdout:', stdout)
            console.log('stderr:', stderr)
            callback(stdout)
        })
      }
  }
 
var execWithCallback = new execWithCallback()
execWithCallback.execCommand(yourExecCmd, function (result) {
    console.log('result')
    console.log(result)
})

Benefits of next/dynamic with ssr: true

Regular import

When using a regular component import, Next.js bundles the component’s code together with the rest of the components for a given route. This usually means you end up with a big chunk containing all the components code for each route.

next/dynamic with ssr: true

When using next/dynamic with ssr: true, Next.js splits the component’s code into a separate chunk (code splitting) and loads that chunk separately (lazy loading).

This means that for the scenario that you described:

import dynamic from 'next/dynamic'
const DynamicButton = dynamic(() => import('./dynamicButton'), { ssr: true })
...
return showButton && <DynamicButton />

The DynamicButton component only gets loaded when showButton is truthy. This has the benefit of reducing the amount of JavaScript that’s loaded on initial page load.

next/dynamic with ssr: false

When using next/dynamic with ssr: false, all the above benefits of the dynamic import also apply. However, the component’s code will not get preloaded on the server and will only run on the client. This is typically useful when the component includes a library or API that only works in the browser.

Next.Js getStaticProps and re-fetching for static build html

Next.Js prior version 13 ( pages/ folder )Next.Js version 13.4 ( app/ folder )
getStaticProps with revalidatefetch(URL, { next: { revalidate: 10 } })use this one
getStaticPropsfetch(URL, { cache: ‘no-store’ })
getServerSidePropsfetch(URL, { cache: ‘force-cache’ })
getStaticPaths()generateStaticParams()

git rename most recent commit

git commit --amend -m "an updated commit message"

git remove local stale branches which already deleted remotely

git fetch --prune origin

React theme brakepoints

  • xs: Extra small devices (less than 600px)
  • sm: Small devices (600px and up)
  • md: Medium devices (900px and up)
  • lg: Large devices (1200px and up)
  • xl: Extra large devices (1536px and up)
<Box
  sx={(theme) => ({
    textAlign: 'center',
    [theme.breakpoints.up('md')]: { textAlign: 'left' },
  })}
>
  TEXT
</Box>

theme.breakpoints.up(‘md’) means @media (min-width: 900px)

So, the above code will set the textAlign to left for screen sizes greater than 900px.

Javascript match prefix

const hostname = "www.someaddress.com"
console.log(!!hostname.startsWith('www.') ? 'matching' : 'not matching')

Next.js usePathname(), useParams(), useSearchParams() in new App Router

'use client'
import {usePathname, useParams, useSearchParams} from "next/navigation";
 
    // folder structure: app/team/[teamName]/page.tsx
    // url: http://localhost:3002/team/something?query=mine
    /* Expected output:
    Pathname: /team/something
    Params: something
    SearchParams: mine
    */
    export default function Page() {
 
    let queryResult: string | null | undefined = null
 
    // params dataset placeholder
    let params: Record<string, string | string[]> | null
 
    const pathName = usePathname()
    params = useParams()
    const searchParams = useSearchParams() 
    queryResult = searchParams?.get('query')    
 
    return (
        <>
        <div><span>Pathname: </span>{pathName}</div>
        <div><span>Params: </span>{params?.teamName}</div>
        <div><span>SearchParams: </span>{queryResult}</div>
        </>
    )
}