Skip to content

Commit

Permalink
feat: use effect skip first render
Browse files Browse the repository at this point in the history
  • Loading branch information
emccorson committed Feb 29, 2024
1 parent e74bf73 commit b7d753d
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 5 deletions.
9 changes: 5 additions & 4 deletions apps/namada-interface/src/App/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
storeColorMode,
} from "@namada/utils";

import { useEffectSkipFirstRender } from "@namada/hooks";
import {
Namada,
useIntegration,
Expand Down Expand Up @@ -67,7 +68,7 @@ const useOnChainChanged = (): void => {
const refreshMinimumGasPrice = useSetAtom(minimumGasPriceAtom);
const refreshPublicKeys = useSetAtom(isRevealPkNeededAtom);

useEffect(() => {
useEffectSkipFirstRender(() => {
refreshMinimumGasPrice();
refreshPublicKeys();
}, [chain]);
Expand All @@ -79,7 +80,7 @@ const useOnNamadaExtensionAttached = (): void => {
const { namada: attachStatus } = useUntilIntegrationAttached(chain);
const integration = useIntegration("namada") as Namada;

useEffect(() => {
useEffectSkipFirstRender(() => {
(async () => {
if (attachStatus === "attached") {
const connected = !!(await integration.isConnected());
Expand All @@ -95,7 +96,7 @@ const useOnNamadaExtensionConnected = (): void => {
const refreshChain = useSetAtom(chainAtom);
const refreshAccounts = useSetAtom(accountsAtom);

useEffect(() => {
useEffectSkipFirstRender(() => {
if (connected) {
refreshChain();
refreshAccounts();
Expand All @@ -109,7 +110,7 @@ const useOnAccountsChanged = (): void => {
const refreshBalances = useSetAtom(balancesAtom);
const refreshPublicKeys = useSetAtom(isRevealPkNeededAtom);

useEffect(() => {
useEffectSkipFirstRender(() => {
if (accountsLoadable.state === "hasData") {
refreshBalances();
refreshPublicKeys();
Expand Down
3 changes: 2 additions & 1 deletion packages/hooks/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export * from "./useDebounce";
export * from "./useEffectSkipFirstRender";
export * from "./useEvent";
export * from "./useSanitizedParams";
export * from "./useSanitizedLocation";
export * from "./useSanitizedParams";
export * from "./useUntil";
16 changes: 16 additions & 0 deletions packages/hooks/src/useEffectSkipFirstRender.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { useEffect, useRef } from "react";

/**
* The same as useEffect, but does not run the effect on the first render.
*/
export const useEffectSkipFirstRender: typeof useEffect = (effect, deps) => {
const firstRender = useRef(true);

useEffect(() => {
if (firstRender.current) {
firstRender.current = false;
} else {
effect();
}
}, deps);
};

0 comments on commit b7d753d

Please sign in to comment.