Created
May 11, 2020 20:00
-
-
Save ryanto/e2d73365e427e4bbde2127dd6d563a60 to your computer and use it in GitHub Desktop.
Depends on. Think of it like a useEffect where you unapologetically use the dependencies list to control when the effect should run.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { usePrevious } from "./use-previous"; | |
import { useRef, useEffect } from "react"; | |
export const useDependsOn = ( | |
value, | |
functionToRun, | |
{ initial = true } = {} | |
) => { | |
let serialized = JSON.stringify(value); | |
let previous = usePrevious(serialized); | |
let shouldRun = useRef(initial); | |
let isFirstRender = useRef(true); | |
if (serialized !== previous.current && (!isFirstRender.current || initial)) { | |
shouldRun.current = true; | |
} | |
useEffect(() => { | |
if (shouldRun.current) { | |
functionToRun(); | |
shouldRun.current = false; | |
} | |
isFirstRender.current = false; | |
}); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useRef, useEffect } from "react"; | |
export const usePrevious = (value) => { | |
let ref = useRef(); | |
useEffect(() => { | |
ref.current = value; | |
}); | |
return ref; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This hook lets you write a function that will run whenever a specific value in your render changes. Think of it as a way to solve the "classic componentDidMount bug" where you forget to handle updating props with componentDidUpdate.
It's not the same as
useEffect
because it lets you opt out of dependencies that "cannot change" from your business logic's point of view. In the above example we don't setfetchUser
orfetchUserCommentsForPost
as things we depend on because even if the identity of those functions happen to change we know that the business logic does not.This can help prevent unexpected effect calls when things we do not care about change.