Skip to content

Instantly share code, notes, and snippets.

@mauriciord
Created February 28, 2020 19:40
Show Gist options
  • Save mauriciord/c725ef53241c77ab7f5249dd0d5c2614 to your computer and use it in GitHub Desktop.
Save mauriciord/c725ef53241c77ab7f5249dd0d5c2614 to your computer and use it in GitHub Desktop.
useState and useSafeSetState

Example

import { useSafeSetState } from './custom';

// ...
const [state, safeSetState] = useSafeSetState({ name: '', email: '' })
// ...
import { useReducer, useEffect, useRef } from 'react'
function useSetState(initialState) {
return useReducer(
(state, newState) => ({...state, ...newState}),
initialState,
)
}
function useSafeSetState(initialState) {
const [state, setState] = useSetState(initialState)
const mountedRef = useRef(false)
useEffect(() => {
mountedRef.current = true
return () => (mountedRef.current = false)
}, [])
const safeSetState = (...args) => mountedRef.current && setState(...args)
return [state, safeSetState]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment