Hooks
February 3, 2025
In react, the concept of side effects encompasses any operation that reach outside the functional scope of a react component. These operations can effect other components, interact with the browser, or perform asynchronous data fetching
Anything that is not related to rendering, not related to operations on DOM.
Hooks
Hooks were introduced in React 16.8
that allows used to use state and other React features without writing a class. They are functions that let you "hook into" React state and lifecycle features from functional components.
They enable functional components to have access to stateful logic and lifecycle features, which were previously only possible in class components.
Common Hooks are:
useState
useEffect
useCallback
useMemo
useRef
useContext
useState
function App() {
const [count, setCount] = useState(0);
return (
<div>
<button onClick={function() {
setCount(count + 1);
}}>Click me {count}</button>
</div>
)
}
Lets you describe the state of the app. Whenever state updates, a re-render is triggered which finally results in DOM update
useEffect
The useEffect
hook allows you to perform side effects in functional components. Side effects are operations that can affect other components or can't be done during rendering, such as data fetching.
Helps us to use lifecycle functions.
The useEffect
serves the same purpose as componentDidMount
, componentDidUpdate
, componentWillUnmount
in React class component
function App() {
const [todos, setTodos] = useState([]);
useEffect(() => {
fetch("https://localhost:3000/todos")
.then(async (res) => {
const json = await res.json();
setTodos(json.todos);
})
}, [])
return (
{todos.map(todo => <Todo key={todo.id} title={todo.title})}
)
}
You can return a function from the useEffect
which will run when the component unmounts
useEffect(() => {
console.log("Component mounted");
return () => {
console.log("Component unmounted")
}
}, [])
So suppose the dependency array contains todos, and a change in todos occurs. Therefore the component will first unmount (runs the function in return) then the new updated component is mounted (runs the code in useEffect that is outsside the return statement)
useMemo
What is memoization? It means remembering the output given an input and not computing it again for the same input
Helps in reducing renders when the input has not changed. (Similar to caching?)
useCallback
useCallback
is used to memoize functions, which can help in optimizing the performance of the application especially in cases where child components that rely on reference equality to prevent unnecessary renders
function App() {
const sum = useCallback(({a,b}) => {
return a+b;
}, [])
}
useCallback
is not about minimizing the amount of code that is run, it is about not rendering a child component, if the function hasn't/doesn't need to change across renders
What's the difference between memo
,useMemo
and useCallback
?
===memo
lets you skip re-rendering a component=== when its props are not changed whereas, useMemo
is a hook that lets you ==cache the result of calculation between re-renders==. useCallback
is a hook that lets you ==cache the function definition between re-renders.==
Custom Hooks
A custom hook is effectively a function, but with the following properties:
- Uses another hook internally (
useState
,useEffect
, etc.) - Starts with
use
Examples of custom hooks are:
- Data fetching hooks
- Browser functionality hooks -
useOnlineStatus
,useWindowSize
,useMousePosition
- Performance/Timer based -
useInterval
,useDebounce