Master React Hooks including useState, useEffect, useContext, useReducer, and custom hooks with production-grade patterns
Provides production-ready React Hooks patterns including useState, useEffect, useContext, custom hooks like useFetch and useDebounce, and performance optimization techniques. Use when building React components requiring state management, side effects, or reusable logic.
/plugin marketplace add pluginagentmarketplace/custom-plugin-react/plugin install react-developer-roadmap@pluginagentmarketplace-reactThis skill inherits all available tools. When active, it can use any tool Claude has access to.
assets/config.yamlreferences/GUIDE.mdscripts/helper.pyMaster React Hooks patterns including built-in hooks (useState, useEffect, useContext, useReducer, useCallback, useMemo) and custom hook development for reusable logic.
const [state, setState] = useState(initialValue);
// Lazy initialization for expensive computations
const [state, setState] = useState(() => expensiveComputation());
// Functional updates when state depends on previous value
setState(prev => prev + 1);
useEffect(() => {
// Side effect code
const subscription = api.subscribe();
// Cleanup function
return () => {
subscription.unsubscribe();
};
}, [dependencies]); // Dependency array
const value = useContext(MyContext);
// Best practice: Create custom hook
function useMyContext() {
const context = useContext(MyContext);
if (!context) {
throw new Error('useMyContext must be within Provider');
}
return context;
}
const [state, dispatch] = useReducer(reducer, initialState);
function reducer(state, action) {
switch (action.type) {
case 'INCREMENT':
return { count: state.count + 1 };
case 'DECREMENT':
return { count: state.count - 1 };
default:
return state;
}
}
const memoizedCallback = useCallback(
() => {
doSomething(a, b);
},
[a, b], // Dependencies
);
const memoizedValue = useMemo(
() => computeExpensiveValue(a, b),
[a, b]
);
const ref = useRef(initialValue);
// DOM access
const inputRef = useRef(null);
<input ref={inputRef} />
inputRef.current.focus();
// Mutable value that doesn't trigger re-render
const countRef = useRef(0);
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
let cancelled = false;
fetch(url)
.then(res => res.json())
.then(data => {
if (!cancelled) {
setData(data);
setLoading(false);
}
})
.catch(err => {
if (!cancelled) {
setError(err);
setLoading(false);
}
});
return () => {
cancelled = true;
};
}, [url]);
return { data, loading, error };
}
function useLocalStorage(key, initialValue) {
const [storedValue, setStoredValue] = useState(() => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
return initialValue;
}
});
const setValue = (value) => {
try {
const valueToStore = value instanceof Function ? value(storedValue) : value;
setStoredValue(valueToStore);
window.localStorage.setItem(key, JSON.stringify(valueToStore));
} catch (error) {
console.error(error);
}
};
return [storedValue, setValue];
}
function useDebounce(value, delay) {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => {
clearTimeout(handler);
};
}, [value, delay]);
return debouncedValue;
}
function usePrevious(value) {
const ref = useRef();
useEffect(() => {
ref.current = value;
}, [value]);
return ref.current;
}
function useToggle(initialValue = false) {
const [value, setValue] = useState(initialValue);
const toggle = useCallback(() => {
setValue(v => !v);
}, []);
return [value, toggle];
}
function useOnClickOutside(ref, handler) {
useEffect(() => {
const listener = (event) => {
if (!ref.current || ref.current.contains(event.target)) {
return;
}
handler(event);
};
document.addEventListener('mousedown', listener);
document.addEventListener('touchstart', listener);
return () => {
document.removeEventListener('mousedown', listener);
document.removeEventListener('touchstart', listener);
};
}, [ref, handler]);
}
function useFetchWithAbort(url) {
const [state, setState] = useState({ data: null, loading: true, error: null });
useEffect(() => {
const abortController = new AbortController();
fetch(url, { signal: abortController.signal })
.then(res => res.json())
.then(data => setState({ data, loading: false, error: null }))
.catch(err => {
if (err.name !== 'AbortError') {
setState({ data: null, loading: false, error: err });
}
});
return () => abortController.abort();
}, [url]);
return state;
}
function useAuthenticatedApi(url) {
const { token } = useAuth();
const { data, loading, error } = useFetch(url, {
headers: {
Authorization: `Bearer ${token}`
}
});
return { data, loading, error };
}
Can you:
// __tests__/useCustomHook.test.js
import { renderHook, act, waitFor } from '@testing-library/react';
import { useCustomHook } from '../useCustomHook';
describe('useCustomHook', () => {
beforeEach(() => {
jest.clearAllMocks();
});
it('should initialize with default state', () => {
const { result } = renderHook(() => useCustomHook());
expect(result.current.state).toBe(initialValue);
});
it('should handle async operations', async () => {
const { result } = renderHook(() => useCustomHook());
await act(async () => {
await result.current.asyncAction();
});
await waitFor(() => {
expect(result.current.loading).toBe(false);
});
});
it('should cleanup on unmount', () => {
const cleanup = jest.fn();
const { unmount } = renderHook(() => useCustomHook({ onCleanup: cleanup }));
unmount();
expect(cleanup).toHaveBeenCalled();
});
});
function useRetryAsync(asyncFn, options = {}) {
const { maxRetries = 3, backoff = 1000 } = options;
const [state, setState] = useState({ data: null, error: null, loading: false });
const execute = useCallback(async (...args) => {
setState(s => ({ ...s, loading: true, error: null }));
let lastError;
for (let attempt = 0; attempt <= maxRetries; attempt++) {
try {
const data = await asyncFn(...args);
setState({ data, error: null, loading: false });
return data;
} catch (error) {
lastError = error;
if (attempt < maxRetries) {
await new Promise(r => setTimeout(r, backoff * Math.pow(2, attempt)));
}
}
}
setState({ data: null, error: lastError, loading: false });
throw lastError;
}, [asyncFn, maxRetries, backoff]);
return { ...state, execute };
}
Version: 2.0.0 Last Updated: 2025-12-30 SASMP Version: 2.0.0 Difficulty: Intermediate Estimated Time: 2-3 weeks Prerequisites: React Fundamentals Changelog: Added retry patterns, test templates, and observability hooks
This skill should be used when the user asks to "create a slash command", "add a command", "write a custom command", "define command arguments", "use command frontmatter", "organize commands", "create command with file references", "interactive command", "use AskUserQuestion in command", or needs guidance on slash command structure, YAML frontmatter fields, dynamic arguments, bash execution in commands, user interaction patterns, or command development best practices for Claude Code.
This skill should be used when the user asks to "create an agent", "add an agent", "write a subagent", "agent frontmatter", "when to use description", "agent examples", "agent tools", "agent colors", "autonomous agent", or needs guidance on agent structure, system prompts, triggering conditions, or agent development best practices for Claude Code plugins.
This skill should be used when the user asks to "create a hook", "add a PreToolUse/PostToolUse/Stop hook", "validate tool use", "implement prompt-based hooks", "use ${CLAUDE_PLUGIN_ROOT}", "set up event-driven automation", "block dangerous commands", or mentions hook events (PreToolUse, PostToolUse, Stop, SubagentStop, SessionStart, SessionEnd, UserPromptSubmit, PreCompact, Notification). Provides comprehensive guidance for creating and implementing Claude Code plugin hooks with focus on advanced prompt-based hooks API.