Diving into more React Hooks
What are Side-Effects?
Before we get into the hooks we need to recall what are Side-Effects. Suppose you have a pure function that takes two integers as an argument and returns the sum of those two numbers and the function also has console.log well. Now this console.log has nothing to do with the sum function, therefore, console.log is a side-effect.
What is useEffect React Hook?
The useEffect hook is a built-in hook in React that allows you to run side effects in functional components. Side effects are operations that affect something outside of the component, such as fetching data, updating the DOM, or subscribing to a data source. The useEffect hook is similar to lifecycle methods in class components, but it's more concise and flexible.
Syntax of useEffect Hook is shown below:
useEffect(callback, dependencies)
callback
: A function that contains the side effect logic.dependencies
: An optional array of dependencies that the effect depends on. If any of the dependencies change, the effect will be re-run. If you pass an empty array[]
, the effect will only run once, similar tocomponentDidMount
in class components.
Understanding Dependencies
Dependencies are an important concept in useEffect, as they determine when the effect should be re-run. If any of the dependencies listed in the array change, the effect will be re-run. If no dependencies are provided, the effect will run on every render, which may not be desirable in some cases.
Six Usages of useEffect
This runs after every render:
useEffect(() =>{ //Side-effect } );
This runs once after mounting the initial render:
useEffect(() =>{ //Side-effect } []);
This runs only after the state changes:
useEffect(() =>{ //Side-effect } [state]);
This runs only after props changes:
useEffect(() =>{ //Side-effect } [props]);
This runs after both state and props changes:
useEffect(() =>{ //Side-effect } [state,props]);
This runs for clean-up :
Clean-up: You can use useEffect to clean up resources, such as closing a WebSocket or canceling a network request. The syntax is shown below:
useEffect(() =>{ //Side-effect return () =>{ // Side-effect cleanup }; } [state,props]);
What is useRef hook?
We will start useRef hook with its syntax:
const ref = useRef(initialValue)
useRef : A build-in React hook helps to persist value between re-renders but doesn't re-render the component by any chance. This means that if your component returns some values, it will save that value for its entire lifetime no matter how many times it renders. Secondly, it means that if we update the value that useRef returns then the component is not re-rendered but if by chance the component is re-rendered by any chance, the reference value is persisted despite the re-render.
initialValue: useRef accepts an optional argument. It can be a valid JavaScript value which to set the initial value of the reference.
ref: useRef returns a reference which is a plain JavaScript object with a special property called current.
useRef Key Points
useRef returns an object with a special property called current
Updating the reference value does not cause a re-render of the component
The reference value is persisted between renders.
useState vs useRef
In React, useState
and useRef
are both hooks that allow you to manage state in functional components. However, they serve different purposes and have some key differences:
State management:
useState
is used for managing state that triggers re-renders in your component. It returns a tuple with the current state value and a function to update that state. When the state value changes, the component re-renders to reflect the updated state.Example usage of
useState
:import React, { useState } from 'react'; const Counter = () => { const [count, setCount] = useState(0); const increment = () => { setCount(count + 1); }; return ( <div> <p>Count: {count}</p> <button onClick={increment}>Increment</button> </div> ); };
Direct DOM manipulation:
useRef
is used for accessing and manipulating DOM elements directly without triggering re-renders. It returns a mutable ref object that can be used to store and access the current value of a DOM element, and it does not trigger component re-renders when the ref value changes.Example usage of
useRef
:import React, { useRef, useEffect } from 'react'; const InputFocus = () => { const inputRef = useRef(); useEffect(() => { inputRef.current.focus(); }, []); return ( <div> <input ref={inputRef} type="text" /> <button onClick={() => inputRef.current.focus()}>Focus input</button> </div> ); };
Updating state:
useState
is used when you need to update state and trigger re-renders in your component. On the other hand,useRef
is used when you need to store a mutable value, such as a reference to a DOM element, and you don't want to trigger re-renders.Initial value:
useState
requires an initial value to be provided when declaring the state, whereasuseRef
does not. The initial value foruseState
can be a primitive value, an object, or an array, whileuseRef
can be initialized withnull
or an initial value.Updates triggering re-renders: When using
useState
, updating the state with the state updater function returned byuseState
triggers a re-render of the component, as React needs to update the UI to reflect the new state. However, updating the value of a ref object created withuseRef
does not trigger a re-render, as it is considered a mutable value that does not affect the component's UI.
In summary, useState
is used for managing state that triggers re-renders in your component, while useRef
is used for accessing and manipulating DOM elements directly without triggering re-renders. Both hooks have their specific use cases and should be chosen based on your component's requirements.
Thank you for taking the time to read our blog! I hope you found the information helpful and informative. Your support means a lot to me.
As I strive to continuously improve and provide valuable content, I would greatly appreciate your feedback. If you have any comments, suggestions, or questions, please feel free to share them with me. Your feedback will help me understand your needs better and shape my future content accordingly.
Once again, thank you for being a part of my blogs. I look forward to serving you with more insightful articles in the future. Please stay tuned for more engaging content!