[React] 비슷한 쓰임새의 useState 상태값 모으기

멋진감자·2025년 1월 20일

React

목록 보기
3/3
post-thumbnail

기존 코드

1. 상태관리, 핸들러

  const [isSearching, setIsSearching] = useState(false);
  const [isPicking, setIsPicking] = useState(false);
  const [isAdding, setIsAdding] = useState(false);
  const [isEditing, setIsEditing] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);

  const handleSearchFieldOpen = () => setIsSearching(true);
  const handleSearchFieldClose = () => setIsSearching(false);

  const handleTimePickerOpen = () => setIsPicking(true);
  const handleTimePickerClose = () => setIsPicking(false);

  const handleAddRecordOpen = () => setIsAdding(true);
  const handleAddRecordClose = () => setIsAdding(false);

  const handleEditRecordOpen = () => setIsEditing(true);
  const handleEditRecordClose = () => setIsEditing(false);

  const handleDeleteRecordOpen = () => setIsDeleting(true);
  const handleDeleteRecordClose = () => setIsDeleting(false);

2. 사용 예시

<popup onClose={handleEditRecordClose} />

모여라

상태관리, 핸들러

  const [state, setState] = useState({
    isSearching: false,
    isPicking: false,
    isAdding: false,
    isEditing: false,
    isDeleting: false,
  });
  
  const openState = (key: string) =>
    setState((prev) => ({ ...prev, [key]: true }));
  const closeState = (key: any) =>
    setState((prev) => ({ ...prev, [key]: false }));

사용 예시

<popup onClose={() => closeState('isEditing')} />

그른데

정리하고보니
핸들러를 건너뛴 그냥..
한 곳에 모으기만 한 코드 같다

profile
난멋져

0개의 댓글