React Hooks 7pgs
React Hooks 7pgs
React Hooks are functions that let you "hook into" React state and lifecycle features in function components. They were introduced in
React 16.8, enabling you to use state and other React features without writing a class.
2. Reuse Logic: With custom hooks, you can reuse stateful logic between components.
3. Better Organization: Hooks separate logic from UI rendering, keeping your components cleaner.
8. useLayoutEffect : Similar to useEffect , but fires synchronously after all DOM mutations.
useState
A Hook that lets you add state to functional components.
Definition:
useState is a Hook that returns a stateful value and a function to update it. The initial state is passed to useState, and it preserves the
state across re-renders.
Syntax:
Code Example:
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click Me</button>
</div>
);
}
When to Use:
Use useState when you need to manage simple state like a counter, form input, or toggling a feature.
useEffect
React Hooks 1
A Hook that lets you perform side effects in functional components.
Definition:
useEffect runs after the render, allowing you to perform operations such as data fetching, subscriptions, or manual DOM manipulations. It
useEffect(() => {
// Side effect logic here
return () => {
// Cleanup (optional)
};
}, [dependencies]);
Code Example:
function Timer() {
const [count, setCount] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setCount(prevCount => prevCount + 1);
}, 1000);
When to Use:
Fetching data.
Subscribing to events.
useContext
A Hook that lets you access the React context value directly.
Definition:
useContext accepts a context object (the value returned from React.createContext ) and returns the current context value for that context.
Context provides a way to pass data through the component tree without having to pass props manually at every level.
Syntax:
Code Example:
React Hooks 2
function ThemedButton() {
const theme = useContext(ThemeContext);
return <button className={theme}>I am styled by theme context!</button>;
}
When to Use:
Use useContext to access global values like themes, authentication status, or settings.
useRef
A Hook that lets you persist values across renders or directly reference a DOM element.
Definition:
useRef returns a mutable object whose .current property is initialized to the passed argument ( initialValue ). The returned object persists
throughout the component's lifecycle.
Syntax:
Code Example:
function InputFocus() {
const inputRef = useRef(null);
return (
<div>
<input ref={inputRef} type="text" placeholder="Click the button to focus me" />
<button onClick={focusInput}>Focus Input</button>
</div>
);
}
When to Use:
useReducer
A Hook that lets you manage complex state logic in functional components.
Definition:
React Hooks 3
useReducer is an alternative to useState for managing more complex state logic. It takes a reducer function and an initial state as arguments
Code Example:
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
<button onClick={() => dispatch({ type: 'reset' })}>Reset</button>
</div>
);
}
When to Use:
For managing complex state logic (e.g., state with multiple sub-values).
useMemo
A Hook that lets you optimize performance by memoizing a computed value.
Definition:
useMemo accepts a "create" function and a dependency array. It memoizes the result of the "create" function and recomputes it only when
one of the dependencies has changed.
Syntax:
React Hooks 4
import React, { useState, useMemo } from 'react';
function ExpensiveCalculationExample() {
const [count, setCount] = useState(0);
const [input, setInput] = useState('');
return (
<div>
<p>Count: {count}</p>
<p>Result of expensive calculation: {memoizedValue}</p>
<button onClick={() => setCount(count + 1)}>Increment Count</button>
<input
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="This won't trigger recalculation"
/>
</div>
);
}
When to Use:
useCallback
A Hook that lets you memoize a callback function.
Definition:
useCallback returns a memoized version of the callback function that only changes if one of its dependencies has changed. It is useful for
preventing unnecessary re-creations of functions.
Syntax:
function ParentComponent() {
const [count, setCount] = useState(0);
React Hooks 5
console.log('Button clicked!');
}, []); // No dependencies, so function is memoized
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment Count</button>
<Button handleClick={memoizedHandleClick} />
</div>
);
}
When to Use:
When the same function is used across renders and depends on stable inputs.
useLayoutEffect
A Hook that fires synchronously after all DOM mutations.
Definition:
useLayoutEffect is similar to useEffect , but it fires synchronously after DOM updates and before the browser paints. It is used for reading
Syntax:
useLayoutEffect(() => {
// Synchronous effect logic
return () => {
// Cleanup (optional)
};
}, [dependencies]);
function MeasureWidth() {
const [width, setWidth] = useState(0);
const divRef = useRef(null);
useLayoutEffect(() => {
setWidth(divRef.current.offsetWidth); // Access DOM width
}, []);
return (
<div>
<div ref={divRef} style={{ width: '50%' }}>
Resize me
</div>
<p>Width of div: {width}px</p>
</div>
);
}
React Hooks 6
When to Use:
When you need to measure or modify DOM elements before the browser paints.
Summary Table
Notes:
useState is perfect for simpler, component-specific state management.
useEffect handles side effects and can run on mount, unmount, or state updates, making it the most versatile hook.
useContext simplifies state sharing across components, reducing the need for intermediate props.
useRef , useReducer , useMemo , useCallback , and useLayoutEffect are generally used in more advanced scenarios where performance or
complexity requires specific solutions.
React Hooks 7