Beyond the everyday hooks
Hooks let functional components tap into React's state lifecycle without being rewritten as classes. useEffect, useState and useContext cover most day-to-day work. React has shipped more of them since hooks landed in version 16.8, and several rarely come up until a specific problem calls for them.
useReducer: collective state management
useReducer is a state tool that serves as an alternative to useState. Where useState makes you update each piece of state individually, useReducer tracks several states or actions together and handles the re-render. That makes it the easier choice when a complex project juggles many states.
Reach for it when multiple states need to be tracked collectively: it separates a component's state management from its rendering logic.
It takes three arguments, the last optional:
- a reducer function
initialState- an
initfunction (optional)
const [state, dispatch] = useReducer(reducer, initialState)
const [state, dispatch] = useReducer(reducer, initialState initFunction) // in the case where you initialize with the optional 3rd argument
The example below builds a small interface with a text input, a counter and a button, each interaction updating state. The reducer's switch-case collects the cases in one place instead of setting them up one at a time — the advantage useReducer offers in complex applications.
import { useReducer } from 'react';
const reducer = (state, action) => {
switch (action.type) {
case 'INCREMENT':
return { ...state, count: state.count + 1 };
case 'DECREMENT':
return { ...state, count: state.count - 1 };
case 'USER_INPUT':
return { ...state, userInput: action.payload };
case 'TOGGLE_COLOR':
return { ...state, color: !state.color };
default:
throw new Error();
}
}
function App() {
const [state, dispatch] = useReducer(reducer, { count: 0, userInput: '', color: false })
return (
<main className="App, App-header" style={{ color: state.color ? '#000' : '#FF07FF'}}>
<input style={{margin: '2rem'}}
type="text"
value={state.userInput}
onChange={(e) => dispatch({ type: 'USER_INPUT', payload: e.target.value })}
/>
<br /><br />
<p style={{margin: '2rem'}} >{state.count}</p>
<section style={{margin: '2rem'}}>
<button onClick={(() => dispatch({ type: 'DECREMENT' }))}>-</button>
<button onClick={(() => dispatch({ type: 'INCREMENT' }))}>+</button>
<button onClick={(() => dispatch({ type: 'TOGGLE_COLOR' }))}>Color</button>
</section>
<br /><br />
<p style={{margin: '2rem'}}>{state.userInput}</p>
</main>
);
}
export default App;
useRef: persistent values without re-renders
Primarily, useRef creates refs on elements to access the DOM. It returns an object with a .current property that lives for the component's whole lifecycle, so data can persist between renders. Updating the ref never triggers a re-render.
Use it when you need to:
- manipulate the DOM with stored mutable information
- read information from child components (nested elements)
- place focus on an element
It fits best for storing mutable data without causing a re-render. The hook accepts a single argument: the initial value.
const newRefComponent = useRef(initialValue);
In the example, useRef and useState together count how many times an app renders updated state as you type. Every keystroke updates state, yet no full re-render is triggered.
import './App.css'
function App() {
const [anyInput, setAnyInput] = useState(" ");
const showRender = useRef(0);
const randomInput = useRef();
const toggleChange = (e) => {
setAnyInput (e.target.value);
showRender.current++;
}
const focusRandomInput = () => {
randomInput.current.focus();
}
return (
<div className="App">
<input className="TextBox"
ref ={randomInput} type="text" value={anyInput} onChange={toggleChange}
/>
<h3>Amount Of Renders: {showRender.current}</h3>
<button onClick={focusRandomInput}>Click To Focus On Input </button>
</div>
);
}
export default App;
useImperativeHandle: calling into a child
Props flow down from parent to child, so a child can call functions the parent passes it. The reverse direction isn't available the same way. useImperativeHandle opens it up: a parent can reach the functions defined inside a child component.
The wiring runs through five steps:
- define a function in the child component
- add a
refin the parent - use
forwardRefso that definedrefreaches the child - expose the child's functions through the
refwithuseImperativeHandle
This suits cases where the parent must react to changes in the child — shifted focus, incrementing and decrementing, blurred elements — so the parent can be updated accordingly.
useImperativeHandle (ref, createHandle, [dependencies])
The example uses two buttons, one in the parent and one in the child. Clicking the parent's button pulls data from the child and manipulates the parent, while the child's button passes nothing downward, underlining that data travels in the opposite direction here.
// Parent component
import React, { useRef } from "react";
import ChildComponent from "./childComponent";
import './App.css';
function useImperativeHandle() {
const controlRef = useRef(null);
return (
onClick={
() => {
controlRef.current.controlPrint();
}
}
>
Parent Box
);
}
export default useImperativeHandle;
// Child component
import React, { forwardRef, useImperativeHandle, useState } from "react";
const ChildComponent = forwardRef((props, ref) => {
const [print, setPrint] = useState(false);
useImperativeHandle(ref, () => ({
controlPrint()
{ setPrint(!print); },
})
);
return (
<>
Child Box
{ print && I am from the child component }
);
});
export default ChildComponent;
useMemo: memoizing calculated values
Each time state updates and a component re-renders, useMemo stops React from recalculating values — useful for large computations where it cuts latency. It accepts a function and returns that function's return value, caching it until a dependency changes.
That caching process is called memoization: the result of an earlier request is remembered and reused instead of recomputing the math.
Heavy calculations are its best fit, storing a value for reuse across later state changes. Overusing it can backfire by consuming your app's memory.
useMemo( () =>
{ // Code goes here },
[]
)
The demo below checks whether a number is even or odd and then squares it when a button is clicked. A loop padded with extra zeros raises the computation load; thanks to useMemo, the value comes back in split seconds.
// UseMemo.js
import React, { useState, useMemo } from 'react'
function Memo() {
const [memoOne, setMemoOne] = useState(0);
const incrementMemoOne = () => { setMemoOne(memoOne + 1) }
const isEven = useMemo(() => {
let i = 0 while (i < 2000000000) i++ return memoOne % 2 === 0
},
[memoOne]);
const square = useMemo(()=> {
console.log("squared the number"); for(var i=0; i < 200000000; i++);
return memoOne * memoOne;
},
[memoOne]);
return (
Memo One -
{ memoOne }
{ isEven ? 'Even' : 'Odd' } { square }
);
}
export default Memo
useMemo resembles useCallback, except that it stores the memoized value a function produces, while useCallback stores the function itself.
useCallback: memoizing functions
Both hooks rely on memoization to cache something for later. useCallback stores and returns a function, where useMemo caches a function's computed value.
It's a performance optimization: the memoized callback and its dependencies are kept without a re-render.
const getMemoizedCallback = useCallback (
() => { doSomething () }, []
);
{ useCallback, useState } from "react";
import CallbackChild from "./UseCallback-Child";
import "./App.css"
export default function App() {
const [toggle, setToggle] = useState(false);
const [data, setData] = useState("I am a data that would not change at every render, thanks to the useCallback");
const returnFunction = useCallback(
(name) =>
{ return data + name; }, [data]
);
return (
onClick={() => {
setToggle(!toggle);
}}
>
{" "}
// Click To Toggle
{ toggle && h1. Toggling me no longer affects any function }
);
}
// The Child component
import React, { useEffect } from "react";
function CallbackChild(
{ returnFunction }
) {
useEffect(() =>
{ console.log("FUNCTION WAS CALLED"); },
[returnFunction]);
return { returnFunction(" Hook!") };
}
export default CallbackChild;
What these five share
This covers only the surface of these hooks, each with its own nuances to weigh. Practicing them in a real application is the way to understand where one fits better than the hook you would normally reach for.
- Intro to React Hooks (Kingsley Silas)
- Hooks at a Glance (React documentation)
- Hooks Cheatsheet (Ohans Emmanuel)
- The Circle of a React Lifecycle (Kingsley Silas)
- Hooks of React Router (Agney Menon)
- Testing React Hooks With Enzyme and React Testing Library (Kingsley Silas)



