I want to make custom hook that will skip first useEffect render and reuse it everywhere.
I made a working example of custom hook:
function useEffectSkipFirst(fn, arr) {
const isFirstRun = useRef(true);
useEffect(() => {
if (isFirstRun.current) {
isFirstRun.current = false;
return;
}
fn();
}, [...arr]);
}
How to use:
useEffectSkipFirst(fn, []);
Problem is that i got a few warnings that i try to understand and hope you can help me:
React Hook useEffect has a missing dependency: 'fn'. Either include it or remove the dependency array. If 'fn' changes too often, find the parent component that defines it and wrap that definition in useCallback. (react-hooks/exhaustive-deps) eslint
React Hook useEffect has a spread element in its dependency array. This means we can't statically verify whether you've passed the correct dependencies. (react-hooks/exhaustive-deps)
Full example code:
import React, { useRef, useEffect, useState } from "react";
import ReactDOM from "react-dom";
function useEffectSkipFirst(fn, arr) {
const isFirstRun = useRef(true);
useEffect(() => {
if (isFirstRun.current) {
isFirstRun.current = false;
return;
}
fn();
}, [...arr]);
}
function App() {
const [clicks, setClicks] = useState(0);
const [date, setDate] = useState(Date.now());
const [useEffectRunTimes, setTseEffectRunTimes] = useState(0);
useEffectSkipFirst(() => {
addEffectRunTimes();
}, [clicks, date]);
function addEffectRunTimes() {
setTseEffectRunTimes(useEffectRunTimes + 1);
}
return (
<div className="App">
<div>clicks: {clicks}</div>
<div>date: {new Date(date).toString()}</div>
<div>useEffectRunTimes: {useEffectRunTimes}</div>
<button onClick={() => setClicks(clicks + 1)}>add clicks</button>
<button onClick={() => setDate(Date.now())}>update date</button>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);