Skip to content

Instantly share code, notes, and snippets.

@kanguki
Last active September 3, 2022 03:33
Show Gist options
  • Save kanguki/eb8ca1146832d9b8efd943e1a137ccae to your computer and use it in GitHub Desktop.
Save kanguki/eb8ca1146832d9b8efd943e1a137ccae to your computer and use it in GitHub Desktop.
react note

useReducer

type Reducer: (state: any, action?: any) => void
type Dispatch: (action?: any) => void
function useReducer (reducer: Reducer, initialState: any) [state: any, dispatch: Dispatch] {
  return [initialState, function(action?: any) {
    reducer(initialState, action)
  }]
}

useCallback

function Xyz() {
  const [count, setCount] = useState(0)
  const childFunc = () => {}
  return (
    <ComponentThatWillRerender />
    <Component x={childFunc} c={count} onClick={()=>setCount(count+1)}/> #here when ComponentThatWillRerender rerenders, childFunc is recreated, i.e change, hence Component is recreated with new props, so it has to rerender, which is not expected because Component doesnt change
  )
}

===============> useCallback

function Xyz() {
  const [count, setCount] = useState(0)
  const childFunc = useCallback(()=> () => {}) //cached unless count changes
  return (
    <ComponentThatWillRerender />
    <Component x={childFunc} c={count} onClick={()=>setCount(count+1)} /> #here when ComponentThatWillRerender rerenders, childFunc is cached, so Component is not rendered again
  )
}

useMemo

function Xyz() {
  const [count, setCount] = useState(0)
  const expensiveComponentRunsWhenCountChange = function() {
    let num = 1 + ... + 1 billion 
    return num
  }
  return (
    <ComponentThatWillRerender /> 
    {expensiveComponentRunsWhenCountChange} #here when ComponentThatWillRerender rerenders, expensiveComponent is recreated, which is not expected as count has not changed
    <Count x={count} onClick={()=>setCount(count+1)}/>
  )
}

===================>useMemo

function Xyz() {
  const [count, setCount] = useState(0)
  const expensiveComponentRunsWhenCountChange = useMemo(()=> function() {
    let num = 1 + ... + 1 billion 
    return num
  },[count]) //cached unless count changes
  return (
    <ComponentThatWillRerender /> 
    {expensiveComponentRunsWhenCountChange} #here when ComponentThatWillRerender rerenders, expensiveComponent is recreated, which is not expected as count has not changed
    <Count x={count} onClick={()=>setCount(count+1)}/>
  )
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment