Skip to content

Instantly share code, notes, and snippets.

@SaiEashwarKS
Created June 28, 2022 10:22
Show Gist options
  • Save SaiEashwarKS/032768adaa9f02de24d85fe432469551 to your computer and use it in GitHub Desktop.
Save SaiEashwarKS/032768adaa9f02de24d85fe432469551 to your computer and use it in GitHub Desktop.
import { useEffect, useRef } from 'react';
import { Hook } from './singletonHookTypes';
export const SingleItemContainer = ({ initValue, useHookBody, applyStateChange, args = [] }: Hook) => {
const lastState = useRef(initValue);
if (typeof useHookBody !== 'function') {
throw new Error(`function expected as hook body parameter. got ${typeof useHookBody}`);
}
const hookReturn = useHookBody(...args);
useEffect(() => {
//apply change to consumers if value has changed
if (lastState.current !== hookReturn) {
lastState.current = hookReturn;
applyStateChange(hookReturn);
}
}, [applyStateChange, JSON.stringify(hookReturn)]); //eslint-disable-line react-hooks/exhaustive-deps
return null;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment