Skip to content

Commit

Permalink
Improve comments on useImmediate* hooks
Browse files Browse the repository at this point in the history
  • Loading branch information
kitten committed Jun 4, 2019
1 parent 84c220d commit 55f1416
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 3 deletions.
2 changes: 1 addition & 1 deletion src/hooks/useImmediateEffect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ enum LifecycleState {

type Effect = () => () => void;

/** This executes an effect immediately on initial render and then treats it as a normal effect */
/** This is a drop-in replacement for useEffect that will execute the first effect that happens during initial mount synchronously */
export const useImmediateEffect = (
effect: Effect,
changes: ReadonlyArray<any>
Expand Down
5 changes: 3 additions & 2 deletions src/hooks/useImmediateState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,15 @@ import { useRef, useEffect, useState, useCallback } from 'react';
type SetStateAction<S> = S | ((prevState: S) => S);
type SetState<S> = (action: SetStateAction<S>) => void;

/** This is a drop-in replacement for useState, limited to object-based state. During initial mount it will mutably update the state, instead of scheduling a React update using setState */
export const useImmediateState = <S extends {}>(init: S): [S, SetState<S>] => {
const isMounted = useRef(false);
const initialState = useRef<S>({ ...init });
const [state, setState] = useState<S>(initialState.current);

// This wraps setState and updates the state mutably on initial mount
// It also prevents setting the state when the component is unmounted
const updateState: SetState<S> = useCallback((action: SetStateAction<S>) => {
// If the component is currently before its initial mount, update
// the state immediately
if (isMounted.current) {
setState(action);
} else if (typeof action === 'function') {
Expand Down

0 comments on commit 55f1416

Please sign in to comment.