React hooks with examples

React hooks are the javaScript functions that manage the state’s behaviour and side effects by isolating them from a component.
Using react hooks, we hook into react lifecycle. The following are the stages of react lifecycle in simple terms, where hooks come into picture: 1. When component mounts 2. When state changes 3. When props changes 4. When context or store changes 5. When component unmounts
For example, at stage 1, 2 -> useState, useEffect are used at stage 4 -> useContext, useReducer are used
React provides a bunch of standard in-built hooks:
useState: To manage states. Returns a stateful value and an updater function to update it.useEffect: To manage side-effects like API calls, subscriptions, timers, mutations, and more.useContext: To return the current value for a context.useReducer: AuseStatealternative to help with complex state management.useCallback: It returns a memorized version of a callback to help a child component not re-render unnecessarily.useMemo: It returns a memoized value that helps in performance optimizations.useRef: It returns a ref object with a.currentproperty. The ref object is mutable. It is mainly used to access a child component imperatively.useLayoutEffect: It fires at the end of all DOM mutations. It's best to useuseEffectas much as possible over this one as theuseLayoutEffectfires synchronously.
1. useState:
Used to declare and track the component’s state variable’s value. State is the data of component we deal with, and that data holds certain values which is used in JSX to render. When there is a change in state, react re-renders the part(JSX) that got changed, it means that the component function gets executed again.
Accepts an optional argument, which can be a valid javascript value, to set initial value to state variable.
Returns array of two values. The first one is the current value of state variable. The second one is the method to update the state variable
const [state, setState] = useState(initialValue);NOTE: We don’t update state variable directly, but by using setState method, because react uses virtual DOM and it updates virtual DOM, it doesn’t update actual DOM. Then differentiation algorithm is applied between these two DOMs and only the changed portion is re-rendered by react.
Example with code:
import React,{ useState } from 'react';
function StateHookExample() {
const white = '#ffffff';
const black = '#000000';
const [isWhite, setIsWhite] = useState(true);
const [hello, setHello] = useState('');
return (
<div style={{backgroundColor: isWhite ? white : black}}>
<button onClick={() => {
setIsWhite( (prevState) => !prevState );
}}>Toggle background</button>
<p style={{color: !isWhite ? white : black}}>{hello}</p>
<button onClick={() => {
setHello('Hello!');
}}>Say hello</button>
</div>
);
}
export default StateHookExample;This example shows two state variables, isWhite and hello. - On clicking on ‘Toggle background’ button, we update(toggle) state variable(isWhite), based on previous state value. - On clicking on ‘Say hello’ button, we just update state variable without considering previous state value.
2. useEffect:
References: https://github.com/Wavez/react-hooks-lifecycle?tab=readme-ov-file https://www.freecodecamp.org/news/react-hooks-fundamentals/