UNPKG

@hhgtech/hhg-components

Version:
45 lines (40 loc) 1.5 kB
'use strict'; var React = require('react'); /** src: https://www.benmvp.com/blog/8-helpful-custom-react-hooks/ * check if we are at first mount */ const useInitialMount = () => { // refs exist across component re-renders, so // we can use it to store a value for the // subsequent renders. We're tracking if it's // the first render, which is initially `true` const isFirst = React.useRef(true); // the very first render, the ref will be // `true`. but we immediately set it to `false` // so that every render after will be `false` if (isFirst.current) { isFirst.current = false; // return true the very first render return true; } // return false every following render return false; }; let GLOBAL_ID = 0; /** src: https://www.benmvp.com/blog/8-helpful-custom-react-hooks/ * Generate Unique ID for both server and client side. Format: hhg-gen-id{number} * This depend on render order, assuming that the order is the same on server and client. */ const useUniqueId = () => { const idRef = React.useRef(''); const isInitialMount = useInitialMount(); // generate the ID for the first render // and store in the ref to remain for // subsequent renders if (isInitialMount) { GLOBAL_ID += 1; idRef.current = `hhg-gen-id${GLOBAL_ID}`; } return idRef.current; }; exports.useInitialMount = useInitialMount; exports.useUniqueId = useUniqueId;