Skip to content

Instantly share code, notes, and snippets.

✍️
Working on something exciting

Alexey Raspopov alexeyraspopov

✍️
Working on something exciting
Block or report user

Report or block alexeyraspopov

Hide content and notifications from this user.

Learn more about blocking users

Contact Support about this user’s behavior.

Learn more about reporting abuse

Report abuse
View GitHub Profile
View useTransitionState.js
function useTransitionState(ref) {
let [pending, setPending] = useState(false);
useLayoutEffect(() => {
let target = ref.current;
let handler = {
handleEvent(event) {
setPending(event.type === 'transitionstart');
}
}
target.addEventListener('transitionstart', handler);
View debounce.js
/**
* @example
* let refetch = debounce((params) => makeRequest('/api', params));
* let prA = refetch(paramsA);
* let prB = refetch(paramsB);
* let prC = refetch(paramsC);
* let prD = refetch(paramsD);
* (prA === prB === prC === prD)
* awaits the last promise
*/
View lib.js
export function useResource(fn, input) {
return useMemo(() => {
let resource = { type: 'Pending', value: null };
resource.value = Promise.resolve(fn(...input))
.then(result => Object.assign(resource, { type: 'Resolved', value: result }))
.catch(error => Object.assign(resource, { type: 'Rejected', value: error }));
return resource;
}, input);
}
View Context.js
// MyContext.js
let MyContext = createContext();
export function MyDataProvider({ children }) {
let state = useState(null);
return <MyContext.Provider value={state} children={children} />
}
export function useData() {
let [data] = useContext(MyContext);
View layout.css
:root {
--gap: 0.5em;
}
.horizontal-stack {
display: flex;
flex-direction: row;
}
.vertical-stack {
display: flex;
flex-direction: column;
View sh.js
let childProcess = require('child_process');
function createHandler(commands) {
return new Proxy(function() {}, {
get(target, property) {
return createHandler(commands.concat(property));
},
apply(target, context, args) {
return new Promise((resolve, reject) => {
let command = commands.concat(args).join(' ');
View generateId.js
function generateId() {
return Math.random().toString(32).substr(2, 8);
}
View useQueryState.js
import { useState, useCallback } from 'react';
let defaultHandler = {
read(defaults) {
return getInitialParams(defaults, window.location.search);
},
write(state) {
let params = getUpdatedParams(state);
window.history.pushState(null, null, '?' + params.toString());
},
View extend.js
/**
* Usage
* function Base() {}
* Base.prototype. // anything
*
* let Child = Base.extend({ prototype }, { static });
* let instance = new Child();
*/
function extend(props, statics) {
let parent = this;
@alexeyraspopov
alexeyraspopov / Patterns.md
Last active Oct 22, 2019
Небольшие полезные паттерны для React и хуков
View Patterns.md

Data Injection

Задача: компоненту необходимо получить сторонние данные, которые он не может получить через пропсы.

Проблема: разные источники данных могут иметь разные API, которые влекут за собой необходимость реализации дополнительных аспектов в рамках компонента: useState/useEffect, обработка loading state, доступ к асинхронным API, etc.

Решение: Каждый раз когда компоненту нужны сторонние данные, создавай

You can’t perform that action at this time.