Skip to content

Instantly share code, notes, and snippets.

@caelinsutch
Last active February 12, 2021 01:35
Show Gist options
  • Save caelinsutch/eb15b376091f056d05e74dae9f245f28 to your computer and use it in GitHub Desktop.
Save caelinsutch/eb15b376091f056d05e74dae9f245f28 to your computer and use it in GitHub Desktop.
useReducer
// 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