Solution For disabling UseEffect initial render

useEffect hook’s callback gets called during the initial render

export default function App() {
const [press, setPress] = useState(false);
const [pressed, setPressed] = useState(false);

useEffect(() => {
setPressed(true);
}, [press]);

return (
<div className="App">
{pressed && <div>The button has been pressed!</div>}
<button
onClick={() => {
setPress(true);
}}
>
Click!
</button>
</div>
);
import React, { useState, useEffect } from "react";
import "./styles.css";

export default function App() {
const [press, setPress] = useState(false);
const [pressed, setPressed] = useState(false);

let initialRender=true;
useEffect(() => {
if(initialRender){
initialRender=false;
} else{
setPressed(true);
}
}, [press]);

return (
<div className="App">
{pressed && <div>The button has been pressed!</div>}
<button
onClick={() => {
setPress(true);
}}
>
Click!
</button>
</div>
);
}

Preventing useEffect callback during the initial render

Let’s turn this into a custom a hook

import { useEffect, EffectCallback, DependencyList, useRef } from "react";

/**
* This hook gets called only when the dependencies change but not during initial render.
*
* @param {EffectCallback} effect The `useEffect` callback function.
* @param {DependencyList} deps An array of dependencies.
*
* @example
* ```
* useNonInitialEffect(()=>{
* alert("Dependency changed!");
* },[dependency]);
* ```
*/
export const useNonInitialEffect = (effect: EffectCallback, deps?: DependencyList) => {
const initialRender = useRef(true);

useEffect(() => {
let effectReturns: void | (() => void | undefined) = () => {};

if (initialRender.current) {
initialRender.current = false;
} else {
effectReturns = effect();
}

if (effectReturns && typeof effectReturns === "function") {
return effectReturns;
}
}, deps);
};

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store