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 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';
export function useQueryState(defaults) {
let [state, setState] = useState(() => getInitialParams(defaults));
let updateState = useCallback(patch => {
setState(state => {
let newState = Object.assign({}, state, patch);
let params = getUpdatedParams(newState);
window.history.replaceState(null, null, '?' + params.toString());
return newState;
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 15, 2019
Небольшие полезные паттерны для React и хуков
View Patterns.md

Data Injection

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

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

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

View useInterval.js
function useInterval(callback, delay) {
let handler = useRef(callback);
useEffect(() => {
handler.current = callback;
}, [callback]);
useEffect(() => {
let timer = setInterval(() => handler.current(), delay);
return () => clearInterval(timer);
View Refactoring.md

Given a function component

export default function MyComponent({ value }) {
  return (
    <div>
      <p>{value}</p>
    </div>
  );
}
View ReactErrorBoundary.js
export class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { error: null };
}
static get defaultProps() {
return { fallback: null, onError: () => null };
}
You can’t perform that action at this time.