Developer Code Snippets

Explore helpful, reusable code snippets for React, Next.js, and modern JavaScript.

React useState Example

A simple example of using the useState hook in React to manage component state dynamically.

import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <button onClick={() => setCount(count + 1)}>
      Count: {count}
    </button>
  );
}

export default Counter;

Fetch Data in Next.js

Fetching data from an API using getServerSideProps in Next.js for server-side rendering.

export async function getServerSideProps() {
  const res = await fetch('https://api.example.com/data');
  const data = await res.json();

  return { props: { data } };
}

React useEffect API Call

Using the useEffect hook to fetch data from an API after the component mounts.

import React, { useEffect, useState } from 'react';

function UserList() {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/users')
      .then((res) => res.json())
      .then((data) => setUsers(data));
  }, []);

  return (
    <ul>
      {users.map((user) => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}

export default UserList;

Next.js Dynamic Route Example

Example of dynamic routing in Next.js using [id].js and getStaticPaths.

export async function getStaticPaths() {
  const res = await fetch('https://api.example.com/posts');
  const posts = await res.json();

  const paths = posts.map((post) => ({ params: { id: post.id.toString() } }));

  return { paths, fallback: false };
}

export async function getStaticProps({ params }) {
  const res = await fetch(`https://api.example.com/posts/${params.id}`);
  const post = await res.json();

  return { props: { post } };
}

export default function Post({ post }) {
  return <h1>{post.title}</h1>;
}

Debounce Function in JavaScript

A reusable debounce utility function to delay execution until the user stops typing.

function debounce(func, delay) {
  let timeout;
  return function(...args) {
    clearTimeout(timeout);
    timeout = setTimeout(() => func.apply(this, args), delay);
  };
}

// Example usage:
const handleSearch = debounce((query) => {
  console.log('Searching for:', query);
}, 300);

Custom Hook - useLocalStorage

A custom React hook to sync state with localStorage.

import { useState, useEffect } from 'react';

export function useLocalStorage(key, initialValue) {
  const [value, setValue] = useState(() => {
    const stored = localStorage.getItem(key);
    return stored ? JSON.parse(stored) : initialValue;
  });

  useEffect(() => {
    localStorage.setItem(key, JSON.stringify(value));
  }, [key, value]);

  return [value, setValue];
}

React Context Example

Using React Context to manage global state for theme switching.

import React, { createContext, useContext, useState } from 'react';

const ThemeContext = createContext();

export function ThemeProvider({ children }) {
  const [theme, setTheme] = useState('light');

  const toggleTheme = () => {
    setTheme((prev) => (prev === 'light' ? 'dark' : 'light'));
  };

  return (
    <ThemeContext.Provider value={{ theme, toggleTheme }}>
      {children}
    </ThemeContext.Provider>
  );
}

export function useTheme() {
  return useContext(ThemeContext);
}

Async/Await Error Handling

Example of handling errors in async/await using try...catch in JavaScript.

async function fetchData() {
  try {
    const res = await fetch('https://api.example.com/data');
    if (!res.ok) throw new Error('Network error');
    const data = await res.json();
    console.log(data);
  } catch (error) {
    console.error('Error fetching data:', error.message);
  }
}

fetchData();