Hooks API Reference
useState Example
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
export default Counter;
useEffect Example
import React, { useState, useEffect } from 'react';
function DataFetcher() {
const [data, setData] = useState(null);
useEffect(() => {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => setData(data))
.catch(error => console.error('Error fetching data:', error));
}, []);
return (
<div>
{data ? (
<p>Data: {JSON.stringify(data)}</p>
) : (
<p>Loading...</p>
)}
</div>
);
}
export default DataFetcher;
useContext Example
import React, { useContext } from 'react';
const ThemeContext = React.createContext('light');
function ThemedButton() {
const theme = useContext(ThemeContext);
return (
<button style={{ background: theme }}>Themed Button</button>
);
}
export default ThemedButton;
useReducer Example
import React, { useReducer } from 'react';
const initialState = { count: 0 };
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
<button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button>
</div>
);
}
export default Counter;
useCallback Example
import React, { useState, useCallback } from 'react';
function InputWithCallback() {
const [value, setValue] = useState('');
const handleChange = useCallback(event => {
setValue(event.target.value);
}, []);
return (
<div>
<input type="text" value={value} onChange={handleChange} />
</div>
);
}
export default InputWithCallback;
useMemo Example
import React, { useMemo } from 'react';
function Fibonacci({ n }) {
const fib = useMemo(() => {
const fibonacci = [0, 1];
for (let i = 2; i <= n; i++) {
fibonacci[i] = fibonacci[i - 1] + fibonacci[i - 2];
}
return fibonacci;
}, [n]);
return (
<div>
<p>Fibonacci Sequence up to {n}: {fib.join(', ')}</p>
</div>
);
}
export default Fibonacci;
useRef Example
import React, { useRef, useEffect } from 'react';
function TextInputWithFocusButton() {
const inputRef = useRef(null);
useEffect(() => {
inputRef.current.focus();
}, []);
return (
<div>
<input ref={inputRef} type="text" />
<button onClick={() => inputRef.current.focus()}>Focus Input</button>
</div>
);
}
export default TextInputWithFocusButton;
useLayoutEffect Example
import React, { useState, useLayoutEffect } from 'react';
function LayoutEffectComponent() {
const [width, setWidth] = useState(window.innerWidth);
useLayoutEffect(() => {
const handleResize = () => setWidth(window.innerWidth);
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return (
<div>
<p>Window Width: {width}</p>
</div>
);
}
export default LayoutEffectComponent;
useDebugValue Example
import React, { useDebugValue, useState } from 'react';
function useCustomHook(initialValue) {
const [value, setValue] = useState(initialValue);
useDebugValue(value > 10 ? 'Above 10' : 'Below 10');
return [value, setValue];
}
export default useCustomHook;
useDeferredValue Example
import React, { useState, useDeferredValue } from 'react';
function DeferredValueComponent() {
const [value, setValue] = useState('');
const deferredValue = useDeferredValue(value, { timeoutMs: 1000 });
return (
<div>
<p>Current Value: {value}</p>
<p>Deferred Value: {deferredValue}</p>
<input value={value} onChange={e => setValue(e.target.value)} />
</div>
);
}
export default DeferredValueComponent;
useTransition Example
import React, { useState, useTransition } from 'react';
function TransitionComponent() {
const [startTransition, isPending] = useTransition({ timeoutMs: 1000 });
const [text, setText] = useState('Hello');
return (
<div>
<p>{isPending ? 'Saving...' : text}</p>
<button
disabled={isPending}
onClick={() => {
startTransition(() => setText('World'));
}}
>
Change Text
</button>
</div>
);
}
export default TransitionComponent;
useId Example
import React, { useId } from 'react';
function IdComponent() {
const inputId = useId();
return (
<div>
<label htmlFor={inputId}>Name:</label>
<input id={inputId} type="text" />
</div>
);
}
export default IdComponent;
useSyncExternalStore Example
import React, { useState } from 'react';
import { useSyncExternalStore } from 'react-sync';
function SyncComponent() {
const [count, setCount] = useState(0);
useSyncExternalStore('count', count);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
export default SyncComponent;
useInsertionEffect Example
import React, { useEffect } from 'react';
function InsertionEffectComponent() {
useEffect(() => {
console.log('Component inserted into DOM');
return () => {
console.log('Component removed from DOM');
};
}, []);
return (
<div>
Component Lifecycle Example
</div>
);
}
export default InsertionEffectComponent;