This is a collection of useful and most common JavaScript, TypeScript, React, tanstack/react-query and zustand snippets for Visual Studio Code. These snippets speed up my regular development by providing quick access to commonly used functions and structures.
To use these snippets in VS Code:
- Open the Command Palette (
Ctrl + Shift + P
). - Type
"Preferences: Configure User Snippets"
. - Select
"New Global Snippets File"
, or choose an existing snippet file. - Copy and paste the snippets below into the
.json
file. Alternative, you can
Simply type the prefix in VS Code, press Tab, and the snippet will expand!
clg
→console.log('data')
cer
→console.error('data')
cwarn
→console.warn('data')
cinfo
→console.info('data')
ctab
→console.table('data')
fn
→ Function Declarationfunction functionName(parameters) { // function body }
interface
→ TypeScript Interfaceinterface InterfaceName { property: type; }
arrow
→ Arrow Functionconst functionName = (parameters) => { // function body };
forloop
→for (let i = 0; i < array.length; i++) { }
map
→array.map(item => { })
filter
→array.filter(item => { })
reduce
→array.reduce((acc, item) => { }, initialValue)
find
→array.find(item => { })
includes
→array.includes(value)
push
→array.push(item)
pop
→array.pop()
shift
→array.shift()
unshift
→array.unshift(item)
slice
→array.slice(start, end)
splice
→array.splice(start, deleteCount, item)
sort
→array.sort((a, b) => a - b)
reverse
→array.reverse()
keys
→Object.keys(obj)
values
→Object.values(obj)
entries
→Object.entries(obj)
assign
→Object.assign(target, source)
spread
→{ ...obj, newProperty: value }
destruct
→const { key1, key2 } = obj;
obj
→const obj = { key: value };
asyncfn
→ Async Functionasync function functionName(parameters) { try { await task(); } catch (error) { console.error(error); } }
promise
→ Promise with .then/.catchnew Promise((resolve, reject) => { // task }) .then(result => console.log(result)) .catch(error => console.error(error));
usestate
→ useState Hookconst [state, setState] = useState(initialValue)
useeffect
→ useEffect HookuseEffect(() => { // side effects }, [dependencies])
usememo
→ useMemo Hookconst memoizedValue = useMemo(() => computeExpensiveValue, [dependencies])
useref
→ useRef Hookconst refElement = useRef(null);
usecallback
→ useCallback Hookconst memoizedCallback = useCallback((args) => { // function body }, [dependencies]);
usereducer
→ useReducer Hookconst [state, dispatch] = useReducer(reducerFunction, initialState);
fnc
→ Function Component with TypeScript Interfaceimport React from 'react'; interface Props { exampleProp?: string; } function MyComponent({ exampleProp }: Props): JSX.Element { return ( <div> {/* Your component code here */} </div> ); } export default MyComponent;
fnc-query
→ Function Component with Interface and React Queryimport React from 'react'; import { useQuery } from '@tanstack/react-query'; interface Props { exampleProp?: string; } function MyComponent({ exampleProp }: Props): JSX.Element { const { data, error, isLoading } = useQuery({ queryKey: ['yourQueryKey'], queryFn: async () => { const res = await fetch('/api/endpoint'); if (!res.ok) throw new Error('Network response was not ok'); return res.json(); }, }); if (isLoading) return <div>Loading...</div>; if (error) return <div>Error: {(error as Error).message}</div>; return ( <div> {/* Render fetched data here */} <pre>{JSON.stringify(data, null, 2)}</pre> </div> ); } export default MyComponent;
fnc-mutation
→ Function Component with Interface and useMutationimport React from 'react'; import { useMutation } from '@tanstack/react-query'; interface Props { exampleProp?: string; } interface Payload { key: string; } function MyComponent({ exampleProp }: Props): JSX.Element { const mutation = useMutation({ mutationFn: async (newData: Payload) => { const res = await fetch('/api/endpoint', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(newData), }); if (!res.ok) throw new Error('Failed to submit'); return res.json(); }, onSuccess: (data) => { console.log('Success:', data); }, onError: (error) => { console.error('Error:', error); }, }); const handleSubmit = () => { mutation.mutate({ key: 'value' }); }; return ( <div> <button onClick={handleSubmit} disabled={mutation.isPending}> {mutation.isPending ? 'Sending...' : 'Submit'} </button> {mutation.isError && <div>Error: {(mutation.error as Error).message}</div>} {mutation.isSuccess && <div>Success!</div>} </div> ); } export default MyComponent;
fc
→ Function Component with Interface and useMutationimport React from 'react'; function MyComponent({ exampleProp }: Props): JSX.Element { return ( <div> </div> ); } export default MyComponent;
fc-query
→ Functional Component with Interface and React Queryimport React, { FC } from 'react'; import { useQuery } from '@tanstack/react-query'; interface ComponentNameProps { exampleProp?: string; } const ComponentName: FC<ComponentNameProps> = ({ exampleProp }) => { const { data, error, isLoading } = useQuery({ queryKey: ['yourQueryKey'], queryFn: async () => { const res = await fetch('/api/endpoint'); if (!res.ok) throw new Error('Network response was not ok'); return res.json(); }, }); if (isLoading) return <div>Loading...</div>; if (error) return <div>Error: {(error as Error).message}</div>; return <div><pre>{JSON.stringify(data, null, 2)}</pre></div>; }; export default ComponentName;
fc-mutation
→ Functional Component with Interface and useMutationimport React, { FC } from 'react'; import { useMutation } from '@tanstack/react-query'; interface ComponentNameProps { exampleProp?: string; } const ComponentName: FC<ComponentNameProps> = ({ exampleProp }) => { const mutation = useMutation({ mutationFn: async (newData) => { const res = await fetch('/api/endpoint', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(newData), }); if (!res.ok) throw new Error('Failed to submit'); return res.json(); }, onSuccess: (data) => console.log('Success:', data), onError: (error) => console.error('Error:', error), }); const handleSubmit = () => mutation.mutate({ key: 'value' }); return ( <div> <button onClick={handleSubmit} disabled={mutation.isPending}> {mutation.isPending ? 'Sending...' : 'Submit'} </button> {mutation.isError && <div>Error: {(mutation.error as Error).message}</div>} {mutation.isSuccess && <div>Success!</div>} </div> ); }; export default ComponentName;
zustandStoreTS
→ Zustand Storeimport { create } from 'zustand'; interface StoreState { count: number; setCount: (value: number) => void; } const useStore = create<StoreState>((set) => ({ count: 0, setCount: (value) => set({ count: value }), })); export default useStore;
zustandStoreTS
→ Persistent Zustand Storeimport { persist, createJSONStorage } from 'zustand/middleware'; import { create } from 'zustand'; interface StoreState { count: number; setCount: (value: number) => void; } const useStore = create<StoreState>()( persist( (set) => ({ count: 0, setCount: (value) => set({ count: value }), }), { name: 'my-store', storage: createJSONStorage(() => localStorage), } ) ); export default useStore;
unittest
→ Basic Unit Test for a Componentimport { render, screen } from '@testing-library/react'; import { describe, it, expect } from 'vitest'; import ComponentName from './ComponentName'; describe('ComponentName', () => { it('renders correctly', () => { render(<ComponentName />); expect(screen.getByText('ExpectedText')).toBeInTheDocument(); }); });