Skip to content

Commit

Permalink
refactor: ♻️ prevent onChange when component loads (#29)
Browse files Browse the repository at this point in the history
  • Loading branch information
harshzalavadiya authored Oct 1, 2022
1 parent 7f666ea commit 7453a1d
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
7 changes: 4 additions & 3 deletions src/index.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { css, setup } from "goober";
import React, { useEffect, useState } from "react";
import React, { useState } from "react";
import { useDidUpdateEffect } from "./use-did-update-effect";

import cc from "./classnames";
import Tag from "./tag";
Expand Down Expand Up @@ -86,11 +87,11 @@ export const TagsInput = ({
}: TagsInputProps) => {
const [tags, setTags] = useState<any>(value || []);

useEffect(() => {
useDidUpdateEffect(() => {
onChange && onChange(tags);
}, [tags]);

useEffect(() => {
useDidUpdateEffect(() => {
if (JSON.stringify(value) !== JSON.stringify(tags)) {
setTags(value);
}
Expand Down
10 changes: 10 additions & 0 deletions src/use-did-update-effect.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { useEffect, useRef } from "react";

export function useDidUpdateEffect(fn, inputs) {
const didMountRef = useRef(false);

useEffect(() => {
if (didMountRef.current) fn();
else didMountRef.current = true;
}, inputs);
}

0 comments on commit 7453a1d

Please sign in to comment.