Last active
February 12, 2021 01:35
-
-
Save caelinsutch/eb15b376091f056d05e74dae9f245f28 to your computer and use it in GitHub Desktop.
useReducer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This is gross and hard to read | |
const BasicComponent = () => { | |
const [isOpen, setIsOpen] = useState(false); | |
const [name, setName] = useState(''); | |
const [isLoading, setIsLoading] = useState(false); | |
const [error, setError] = useState(null); | |
const [id, setid] = useState(''); | |
return ( | |
// ... | |
) | |
} | |
// Refactored this is a lot easier to read, more modular, and faster! | |
const initialState = { | |
isOpen: false, | |
name: '', | |
isLoading: false, | |
error: null, | |
id: '' | |
} | |
const reducer = (state, action) => { | |
switch (action.type) { | |
case 'setIsOpen': | |
return { ...state, isOpen: action.payload } | |
break; | |
// ... | |
default: | |
return state; | |
} | |
} | |
const BetterComponent = () => { | |
const [state, dispatch] = useReducer(reducer, initialState); | |
return ( | |
// ... | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment