You can find all the code in this post on the repo Github.
Lifecycle-related React custom hooks challenges
useEffectOnce()
import { useEffect, useState } from "react";
function useEffectOnce(effect) {
useEffect(() => {
return effect();
}, []);
}
/* Usage example */
export default function App() {
const [value, setValue] = useState();
useEffectOnce(() => {
setValue("once!");
});
return (
<div>
<p>value: {value}</p>
</div>
);
}
useIsFirstRender()
import { useEffect, useState } from "react";
function useEffectOnce(effect) {
useEffect(() => {
return effect();
}, []);
}
/* Usage example */
export default function App() {
const [value, setValue] = useState();
useEffectOnce(() => {
setValue("once!");
});
return (
<div>
<p>value: {value}</p>
</div>
);
}
useIsMounted()
import { useEffect, useRef } from "react";
function useIsMounted() {
const isMountedRef = useRef(true);
useEffect(() => {
return () => {
isMountedRef.current = false;
};
}, []);
return () => isMountedRef.current;
}
/* Usage example */
export default function App() {
const isFirstMount = useIsMounted();
return (
<div>
<p>Is first mount: {String(isFirstMount())}</p>
</div>
);
}
usePrevious()
import { useRef, useEffect } from "react";
function usePrevious(value) {
const previousRef = useRef();
useEffect(() => {
previousRef.current = value;
}, [value]);
return previousRef.current;
}
/* Usage example */
export default function App() {
const previousValue = usePrevious(1);
return (
<div>
<p>Previous value: {previousValue}</p>
</div>
);
}
useUpdate()
import { useReducer } from "react";
const updateReducer = (num) => (num + 1) % 1_000_000;
function useUpdate() {
const [_, update] = useReducer(updateReducer, 0);
return update;
}
export default function App() {
return <div></div>;
}
useUpdateEffect()
import { useRef, useEffect } from "react";
function useUpdateEffect(effect, deps) {
const isFirstRenderRef = useRef(true);
useEffect(() => {
if (isFirstRenderRef.current) {
isFirstRenderRef.current = false;
return;
}
return effect();
}, deps);
}
export default function App() {
const fetchData = () => {};
const effect = useUpdateEffect(fetchData);
return (
<div>
<p></p>
</div>
);
}