Skip to content

Instantly share code, notes, and snippets.

@gaurangrshah
Last active May 10, 2021 21:55
Show Gist options
  • Save gaurangrshah/205c7009694a8c47b7a2f644fec9340a to your computer and use it in GitHub Desktop.
Save gaurangrshah/205c7009694a8c47b7a2f644fec9340a to your computer and use it in GitHub Desktop.
import { useCallback, useMemo, useRef } from "react";
// unused
export const useFocus = () => {
const htmlElRef = useRef(null);
const setFocus = useCallback(() => {
if (!htmlElRef.current) return;
htmlElRef.current.focus();
}, [htmlElRef]);
return useMemo(() => [htmlElRef, setFocus], [htmlElRef, setFocus]);
};
// use-has-hydrated.js
import { useState, useEffect, useLayoutEffect } from "react";
function useHasHydrated(beforePaint = true) {
const [hasHydrated, setHasHydrated] = useState(false);
// To reduce flicker, we use `useLayoutEffect` so that we return value
// before React has painted to the browser.
// React currently throws a warning when using useLayoutEffect on the server so
// we use useEffect on the server (no-op) and useLayoutEffect in the browser.
const isServer = typeof window === "undefined";
const useEffectFn = beforePaint && !isServer ? useLayoutEffect : useEffect;
useEffectFn(() => {
setHasHydrated(true);
}, []);
return hasHydrated;
}
import { useEffect, useState } from "react";
/**
* @SCOPE: used to check if a component is mounted
* used by:
* - protected
*/
export function useMounted() {
const [mounted, setMounted] = useState(false);
useEffect(() => {
setMounted(true);
return () => setMounted(false);
}, []);
return mounted;
}
import { useEffect, useContext, createContext } from 'react'
import { useLocalData } from './useLocalData'
import { useAuth } from './useAuth'
import { useUi } from './useUi'
const DataContext = createContext()
export function ProvideData({ children }) {
const Data = useProvideData()
return <DataContext.Provider value={Data}>{children}</DataContext.Provider>
}
export const useData = () => {
return useContext(DataContext)
}
const useProvideData = props => {
const localData = useLocalData()
const auth = useAuth()
const ui = useUi()
return {
localData,
auth,
ui
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment