Nuggets
Welcome to the Nuggets page! Here, I’ll share small but valuable pieces of information.
Why Array as useEffect Dependency is a Bad Idea
Using an array directly as a dependency in useEffect can cause an infinite loop because a new array reference is created on every render.
import { useEffect, useMemo } from "react";
const Component = () => {
const array = useMemo(() => [1, 2, 3], []); // Memoize the array
useEffect(() => {
console.log("This runs only when the array changes.");
}, [array]);
return <div>Check the console!</div>;
};
Template Literal Types from Enums in TypeScript
Using template literal types with enums allows you to create a union type of its values dynamically.
enum Status {
PENDING = "PENDING",
APPROVED = "APPROVED",
REJECTED = "REJECTED"
}
type StatusType = `${Status}`; // Equivalent to "PENDING" | "APPROVED" | "REJECTED"
const updateStatus = (status: StatusType) => {
console.log(`Updating status to: ${status}`);
};
updateStatus("APPROVED"); // ✅ Valid
updateStatus("DENIED"); // ❌ Type error