When to use useRef and useReducer hook in your React App
useRef
and useReducer
are two commonly used ones. Both of them serve different purposes and have their own use cases.
In this article, we will explore when to use useRef
and useReducer
hooks in React JS and what benefits they provide.
When to use useRef
Hook
useRef
hook is used to store and manage mutable values that are not part of the component state. These values are retained between component renderings and do not trigger a re-render when changed. useRef
returns an object with a single property named current
which can be assigned any value.
Use cases for useRef
Hook:
- Accessing DOM elements:
useRef
can be used to access DOM elements and control their behavior, for example, setting the focus or scrolling to a specific location. This is useful when working with third-party libraries that require direct access to the DOM. - Caching expensive computations:
useRef
can be used to store the result of a computation and reuse it in subsequent renders. This can save computation time and improve the performance of the component. - Storing previous values:
useRef
can be used to store the previous value of a prop or state. This can be useful in detecting changes and performing certain actions accordingly. - Managing stateful logic:
useRef
can be used to manage stateful logic that is not part of the component state, such as animations, timers, or other side effects.
useRef
Hook Example
Let’s say we want to access the input field of a form and set its focus when the component mounts. We can use useRef
to achieve this
import React, { useRef, useEffect } from 'react';
function Form() {
const inputRef = useRef(null);
useEffect(() => {
inputRef.current.focus();
}, []);
return (
<form>
<input type="text" ref={inputRef} />
<button type="submit">Submit</button>
</form>
);
}
In this example, we create a ref object using useRef
and assign it to the ref
attribute of the input field. We then use the useEffect
hook to set the focus of the input field when the component mounts.
When to use useReducer
Hook
useReducer
hook is used for managing state that involves complex logic and multiple sub-values. It is similar to the useState
hook, but instead of updating the state directly, it dispatches an action object that describes how the state should change. useReducer
returns a tuple with two elements: the current state and a dispatch function.
Use cases for useReducer
Hook:
- Complex state updates:
useReducer
is useful when the state updates involve complex logic and multiple sub-values. It allows the state to be updated in a more declarative and predictable way. - Shared state between components:
useReducer
can be used to manage shared state between multiple components. The state can be passed down as props, or the components can use a context API to access the state. - Undo/Redo functionality:
useReducer
can be used to implement undo/redo functionality by keeping a history of previous states and allowing the user to navigate back and forth. - Server-side rendering:
useReducer
can be used for server-side rendering where the initial state is fetched from the server and passed to the component as a prop.
Let’s say we have a component that displays a counter and a button to increment or decrement the counter. We can use useReducer
to manage the state of the counter and handle the increment and decrement actions:
import React, { useReducer } from 'react';
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
</div>
);
}
In this example, we define a reducer function that handles the increment
and decrement
actions and updates the state accordingly. We then use useReducer
to create a state object with the initial value of { count: 0 }
and a dispatch function that sends actions to the reducer. We pass the state and dispatch function to the child components and use them to update the state when the buttons are clicked.
Conclusion
In summary, useRef
and useReducer
hooks are powerful tools for managing state in React. useRef
is useful for managing mutable values that are not part of the component state, while useReducer
is useful for managing complex state updates and shared state between components. It is important to choose the right hook for the right use case to ensure efficient and maintainable code.
Tags:
-
tag
- React Hooks
Looking for a software developer? Reach out today...