Skip to content

Instantly share code, notes, and snippets.

@lebbe
Last active May 23, 2022 11:50
Show Gist options
  • Select an option

  • Save lebbe/2aeee872a4b3e1f4fd6c80916701b29a to your computer and use it in GitHub Desktop.

Select an option

Save lebbe/2aeee872a4b3e1f4fd6c80916701b29a to your computer and use it in GitHub Desktop.

Revisions

  1. lebbe revised this gist May 23, 2022. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion someHook.ts
    Original file line number Diff line number Diff line change
    @@ -11,7 +11,7 @@ function someHook(object: Record<string, string>) {
    // REST OF HOOK HERE
    }

    // A very simpel comparison function, prefer a more solid one from a decent library
    // A very simple comparison function, prefer a more solid one from a decent library
    function compareObjects(a: Record<string, string>, b: Record<string, string>) {
    const keysA = Object.keys(a)
    const keysB = Object.keys(b)
  2. lebbe revised this gist May 23, 2022. 1 changed file with 8 additions and 0 deletions.
    8 changes: 8 additions & 0 deletions someHook.ts
    Original file line number Diff line number Diff line change
    @@ -9,4 +9,12 @@ function someHook(object: Record<string, string>) {
    }, [object])

    // REST OF HOOK HERE
    }

    // A very simpel comparison function, prefer a more solid one from a decent library
    function compareObjects(a: Record<string, string>, b: Record<string, string>) {
    const keysA = Object.keys(a)
    const keysB = Object.keys(b)

    return keysA.length === keysB.length && !keysA.some(key => a[key] !== b[key])
    }
  3. lebbe revised this gist May 23, 2022. 1 changed file with 7 additions and 0 deletions.
    7 changes: 7 additions & 0 deletions Readme.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,7 @@
    # When relying on an object in useEffect dependency array

    I found this method the best, to ensure that the object is actually different.
    The "compareObjects" function doesn't have to nest deep in this example,
    because the object is restricted to only have strings as field-values (this
    is not checked in runtime, mind you).

  4. lebbe created this gist May 23, 2022.
    12 changes: 12 additions & 0 deletions someHook.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,12 @@
    function someHook(object: Record<string, string>) {
    // REST OF STATE HERE
    const refObject = useRef(object)

    useEffect(function() {
    if(!compareObjects(object, refObject.current) {
    // DO YOUR THINGS HERE
    }
    }, [object])

    // REST OF HOOK HERE
    }