Skip to content

Instantly share code, notes, and snippets.

@belmer
Last active April 1, 2021 12:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save belmer/67923d5fed749e44eeb7944b8f00701d to your computer and use it in GitHub Desktop.
Save belmer/67923d5fed749e44eeb7944b8f00701d to your computer and use it in GitHub Desktop.
useReducer hook instead of useState
// 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