Skip to content

Instantly share code, notes, and snippets.

View jrwebdev's full-sized avatar

James Ravenscroft jrwebdev

  • Auckland, New Zealand
View GitHub Profile
const date = new Date();
useDebugValue(date, date => date.toISOString());
const myNumberRef = useRef(0);
myNumberRef.current += 1;
const MyInput = () => {
const inputRef = useRef<HTMLInputElement>(null);
return <input ref={inputRef} />
}
import MyInput, { MyInputHandles } from './MyInput';
const Autofocus = () => {
const myInputRef = useRef<MyInputHandles>(null);
useEffect(() => {
if (myInputRef.current) {
myInputRef.current.focus();
}
});
export interface MyInputHandles {
focus(): void;
}
const MyInput: RefForwardingComponent<MyInputHandles, MyInputProps> = (
props,
ref
) => {
const inputRef = useRef<HTMLInputElement>(null);
const value = 10;
// inferred as number
const result = useMemo(() => value * 2, [value]);
const multiplier = 2;
// inferred as (value: number) => number
const multiply = useCallback((value: number) => value * multiplier, [multiplier]);
useEffect(() => {
const subscriber = subscribe(options);
return () => {
unsubscribe(subscriber)
};
}, [options]);
type Theme = 'light' | 'dark';
const ThemeContext = createContext<Theme>('dark');
const App = () => (
<ThemeContext.Provider value="dark">
<MyComponent />
</ThemeContext.Provider>
)
const MyComponent = () => {
interface State {
value: number;
}
type Action =
| { type: 'increment' }
| { type: 'decrement' }
| { type: 'incrementAmount'; amount: number };
const counterReducer = (state: State, action: Action) => {
// inferred as number
const [value, setValue] = useState(0);
// explicitly setting the types
const [value, setValue] = useState<number | undefined>(undefined);
const [value, setValue] = useState<Array<number>>([]);
interface MyObject {
foo: string;
bar?: number;