-
-
Notifications
You must be signed in to change notification settings - Fork 118
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Mutation Observer hook #25
Comments
Definitely! I wonder if you would want an API without a callback so that you could use it in combination with let mutationRecord = useMutationObserver(
document.getElementById("to-observe"),
{ attributes: true },
);
let updateAfterMutations = React.useMemo(handleMutations, [mutationRecord]); |
That's another option as well, I think it depends on the usage. I normally use it to process the mutations once as they occur, and the callback is a good fit for that. Using The good thing I see is that the return value of the hook is more easy to understand, the mutation records vs the result of the MutationObserver's callback. However, we could modify it so that if no callback is passed, the value will be the mutationRecords, and then you could use
What do you think? |
Came here to suggests
Here is a demo if you want to explore |
I modified it to always return the callback value, instead of an object. const defaultCallback = mutationList => mutationList;
function useMutationObserver(targetNode, config, callback = defaultCallback) {
const [value, setValue] = useState(undefined);
const observer = useMemo(
() =>
new MutationObserver((mutationList, observer) => {
const result = callback(mutationList, observer);
setValue(result);
}),
[callback]
);
useEffect(
() => {
if (targetNode) {
observer.observe(targetNode, config);
return () => {
observer.disconnect();
};
}
},
[targetNode, config]
);
return value;
} |
Would you be interested to add a
useMutationObserver
hook?My take on the implementation: https://github.com/danielr18/react-hook-mutation-observer/blob/master/index.js
The text was updated successfully, but these errors were encountered: