React Hooks
What are React Hooks ?
Hooks let us use different React features from your components. We can either use the built-in Hooks or combine them to build your own.
Rules of Hooks
Benefits of using React hooks
Built-in and Custom hooks
React have few built-in hooks and can also create our own custom hooks in React.
Built-in hooks:
useState: useState is a React Hook that lets us add a state variable to our component.
const [state, setState] = useState(initialState)
initialState: The value we want the state to be initially.
useState returns an array with exactly two values:
useEffect: useEffect is a React Hook that lets you synchronize a component with an external system.
useEffect(setup, dependencies?)
setup: The function with our Effect’s logic. Our setup function may also optionally return a cleanup function. When our component is added to the DOM, React will run our setup function. After every re-render with changed dependencies, React will first run the cleanup function (if we provided it) with the old values, and then run our setup function with the new values.
optional dependencies: The list of all reactive values referenced inside of the setup code.
useEffect returns undefined
To understand the useEffect hook you first need to understand lifecycle of the component. The lifecycle of the component contains three main parts i.e. mounting, updating and unmounting.
mounting: when the page loads
updating: when the state updates
unmounting: when user leaves the page
Recommended by LinkedIn
but when using React hooks, we can just do everything through the useEffect hook.
useMemo: useMemo is a React Hook utilized for memoizing expensive calculations. It aims to optimize performance by caching the result of a computation and only recomputing it when the dependencies change.
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
useMemo memoizes the result of the function passed as the first argument. It re-executes the function only if any of the dependencies provided in the array ([a, b]) change.
useRef: useRef is a Hook used to create a mutable reference that persists across renders. It's commonly employed to access the DOM or to store mutable values that don't trigger re-renders.
const myRef = useRef(initialValue);
The myRef object persists for the entire lifecycle of the component. It doesn't cause re-renders when its value changes.
useReducer: useReducer is a Hook that offers an alternative to useState for managing complex state logic. It's particularly useful when the state transitions depend on the previous state.
const [state, dispatch] = useReducer(reducer, initialState);
useReducer follows the reducer pattern familiar from Redux. It takes a reducer function and an initial state as arguments, returning the current state and a dispatch function to trigger state transitions.
Custom hooks:
Custom hook is a JavaScript function that encapsulates a specific piece of logic. It allows us to reuse stateful logic across different components, making our codebase cleaner, more organized, and highly maintainable.
The magic happens when we prefix our custom function with “use” — that’s React’s signal that you’re dealing with a custom hook.
Custom hooks can encapsulate any stateful logic, such as fetching data, managing timers, or handling subscriptions. Once defined, they can be reused across multiple components, promoting code modularization and reducing duplication.
Creating our Custom Hook
import { useState } from 'react';
const useCounter = () => {
const [count, setCount] = useState(0);
const increment = () => {
setCount(count + 1);
}
const decrement = () => {
setCount(count - 1);
}
return { count, increment, decrement };
}
export default useCounter;
Using a Custom Hook
import React from 'react';
import useCounter from './useCounter';
const Counter = () => {
const { count, increment, decrement } = useCounter();
return (
<div>
<h1>Count: {count}</h1>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
}
export default Counter;
Use Cases