Last active
January 28, 2022 13:40
-
-
Save ever-dev/151c0cd4bd48a63924bf62c44ef18dd1 to your computer and use it in GitHub Desktop.
Useful hooks - useStateWithCallback, useChanagesEffect
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
const useChangesEffect = (callback, dependencies, dependencyNames = null) => { | |
const prevValues = useRef(dependencies); | |
useEffect(() => { | |
const changes = []; | |
for (let i = 0; i < prevValues.current.length; i++) { | |
if (!shallowEqual(prevValues.current[i], dependencies[i])) { | |
changes.push(dependencyNames ? dependencyNames[i] : i); | |
} | |
} | |
callback(changes); | |
prevValues.current = dependencies; | |
}, dependencies); | |
}; | |
// Usage1 | |
useChangesEffect((changes) => { | |
if (changes.includes(0)) { | |
console.log('dep1 changed'); | |
} | |
if (changes.includes(1)) { | |
console.log('dep2 changed'); | |
} | |
}, [dep1, dep2]); | |
// Usage2 | |
useChangesEffect((changes) => { | |
if (changes.includes('dep1')) { | |
console.log('dep1 changed'); | |
} | |
if (changes.includes('dep2')) { | |
console.log('dep2 changed'); | |
} | |
}, [dep1, dep2], ['dep1', 'dep2']); |
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
const { useState, useRef, useEffect } = require('react'); | |
const useStateWithCallback = (initialState) => { | |
const [state, setState] = useState(initialState); | |
const callbackRef = useRef(() => undefined); | |
const setStateCB = (newState, callback) => { | |
callbackRef.current = callback; | |
setState(newState); | |
}; | |
useEffect(() => { | |
callbackRef.current?.(); | |
}, [state]); | |
return [state, setStateCB]; | |
}; | |
export default useStateWithCallback; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment