Custom hooks

State

functional setState

Code
interface MyState {
   loading: boolean;
   data: any;
   something: string;
}

const [state, setState] = useReducer<Reducer<MyState, Partial<MyState>>>(
  (state, newState) => ({...state, ...newState}),
  {loading: true, data: null, something: ''}
)

useState with a stable link

Lifecicle

useWillMount

Code
function useWillMount(callback) {
  const ref = useRef();

  if (!ref.current) {
    ref.current = {
      value: callback()
    };
  }

  return ref.current.value;
}

Closure

useEvent (useCallback analog)

function App() {
  const [text, setText] = useState("");

  const onClick = useEvent(() => { // <== stable link
    console.log("test:", text);
  });
}

Code
function App() {
  const [count, setCount] = useState(0);
  const [counterObj, setCounterObj] = useState({ firstCount: 0 });
  const [secondObj, setSecondObj] = useState({ secCount: 0 });

  useDeepCompareEffect(() => {
    console.log("counterObj", [count], counterObj, secondObj);
  }, [counterObj]);
}

Forms

useInput

Code
export default function useInput(initialValue) {
    const [value, setValue] = useState(initialValue);

    const onChange = e => {
        setValue(e.target.value)
    }

    return {
        value, onChange
    }
};

Network, geo

useLocation

предоставляет данные о геолокации в реальном времени, а также метрики курса движения и скорости. 🗺️📍 Демо: https://grayscal.es/hooks/use-location

Используйте его для получения информации о близлежащих местах или для определения местоположения пользователей поблизости.

useNetwork

Вы можете узнать скорость передачи данных, тип соединения и статус сети прямо в вашем приложении. Demo: https://grayscal.es/hooks/use-network

Misc

useExternalScript

  const { isLoading, isError } = useExternalScript({
    url,
    onSuccess: () => . . . do smth . . .
  });

useScroll

Code
export default function useScroll(parentRef, childRef, callback) {
    const observer = useRef();

    useEffect(() => {
        const options = {
            root: parentRef.current,
            rootMargin: '0px',
            threshold: 0
        }
        observer.current = new IntersectionObserver(([target]) => {
            if (target.isIntersecting) {
                console.log('intersected')
                callback()
            }
        }, options)

        observer.current.observe(childRef.current)

        return function () {
            observer.current.unobserve(childRef.current)
        };
    }, [callback])
};

Selection

useTextSelection

https://t.me/react_tg/417 отслеживает выделение текста пользователем и его положение на экране! Демо: http://grayscal.es/hooks/use-text-selection

Идеально подходит для всплывающая подсказка "Поделиться", подобно Medium. ✨

Last updated

Was this helpful?