// 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 (
// ...
)
}
Last active
April 1, 2021 12:47
-
-
Save belmer/67923d5fed749e44eeb7944b8f00701d to your computer and use it in GitHub Desktop.
useReducer hook instead of useState
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment