Skip to content

Instantly share code, notes, and snippets.

View treyhuffine's full-sized avatar

Trey Huffine treyhuffine

View GitHub Profile
function useState<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>];
type Dispatch<A> = (value: A) => void;
type SetStateAction<S> = S | ((prevState: S) => S);
import * as React from 'react';
enum ActionType {
Increment = 'increment',
Decrement = 'decrement',
}
interface IState {
count: number;
}
type Dispatch<A> = (value: A) => void;
type Reducer<S, A> = (prevState: S, action: A) => S;
type ReducerState<R extends Reducer<any, any>> = R extends Reducer<infer S, any> ? S : never;
type ReducerAction<R extends Reducer<any, any>> = R extends Reducer<any, infer A> ? A : never;
function useReducer<R extends Reducer<any, any>, I>(
reducer: R,
initializerArg: I & ReducerState<R>,
initializer: (arg: I & ReducerState<R>) => ReducerState<R>
): [ReducerState<R>, Dispatch<ReducerAction<R>>];
function useContext<T>(context: Context<T>): T;
interface Context<T> {
Provider: Provider<T>;
Consumer: Consumer<T>;
displayName?: string;
}
function DelayedEffect(props: { timerMs: number }) {
const { timerMs } = props;
// ** BAD! ** setTimeout implicitly returns a number because the arrow function body isn't wrapped in curly braces
useEffect(() => setTimeout(() => {/* do stuff */}, timerMs), [timerMs])
// **
return null
}
import * as React from 'react';
interface IUser {
username: string;
email: string;
password: string;
}
const ComplexState = ({ initialUserData }) => {
const [user, setUser] = React.useState<IUser | null>(initialUserData);
import * as React from 'react';
const MyComponent: React.FC = () => {
const [count, setCount] = React.useState(0);
return (
<div onClick={() => setCount(count + 1)}>
{count}
</div>
);
};
@treyhuffine
treyhuffine / react-typescript-fc.js
Created February 12, 2019 11:20
React function component with TypeScript
import * as React from 'react'
interface IProps {
// ... props interface
}
// NEW syntax for typing function components
const MyNewComponent: React.FC<IProps> = (props) => {...};
// OLD syntax for typing function components
import React, { useState, useEffect } from 'react';
import './App.css';
const INCREMENTS = [1, 2, 5, 10];
const mockApi = () => {
return new Promise(resolve => {
setTimeout(() => {
const randomInt = Math.ceil(Math.random() * 10);
resolve(randomInt);
@treyhuffine
treyhuffine / react-16-lifecycle.js
Created August 6, 2018 17:07
A summary of the React 16 lifecycle methods
class ComponentWithLifecycle extends React.Component {
// Commonly Used Lifecycle Methods
constructor() {
- Lifecycle: Mounting (before render)
- Purpose: Initialize state
}
componentDidMount() {
- Lifecycle: Mounting (immediately after render)
- Purpose: Initialize state that requires DOM nodes,