Skip to content

Instantly share code, notes, and snippets.

@ever-dev
Last active January 28, 2022 13:40
Show Gist options
  • Save ever-dev/151c0cd4bd48a63924bf62c44ef18dd1 to your computer and use it in GitHub Desktop.
Save ever-dev/151c0cd4bd48a63924bf62c44ef18dd1 to your computer and use it in GitHub Desktop.
Useful hooks - useStateWithCallback, useChanagesEffect
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']);
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