Cleaner and more concise way of handling states in React? [closed]

In my app, SearchParams.tsx is a form that gets the apiResponse from the parent and uses entries in this response to set options for it’s select/dropdown menus for the user to then choose from. I have a lot of states in this component, few for setting the options available and others for tracking the options the user has selected (to submit/post on form submit). I am wondering if there is a more elegant/cleaner/concise way to do this (except combining everything in one object)? Or if having separate states tracking everything individually is a good idea in react? Is one approach better than the other? etc.

Note: I am using a third party API so don’t have any control on that front.

Here is a snippet from SearchParams.tsx:

const SearchParams = ({ apiResponse, speciesSelected }: { apiResponse: SpeciesSelectionResponse| {}, speciesSelected: string }) => {

    const [desiredAge, setDesiredAge] = useState<string>("")
    const [desiredGender, setDesiredGender] = useState<string>("")
    const [desiredGeoRange, setDesiredGeoRange] = useState<string>("35")
    const [desiredColor, setDesiredColor] = useState<string>("")
    const [desiredBreed, setDesiredBreed] = useState<string>("")
    const [zipCode, setZipCode] = useState<string>("")
    const [species, setSpecies] = useState<string>("")
    
    const [ageOptionsAvailable, setAgeOptionsAvailable] = useState<SubObject[]>([])
    const [genderOptionsAvailable, setGenderOptionsAvailable] = useState<SubObject[]>([])
    const [geoRangeOptionsAvailable, setGeoRangeOptionsAvailable] = useState<SubObject[]>([])
    const [colorOptionsAvailable, setColorOptionsAvailable] = useState<SubObject[]>([])
    const [breedOptionsAvailable, setBreedOptionsAvailable] = useState<SubObject[]>([])

    useEffect(() => {
        if (Object.keys(apiResponse).length === 0 && apiResponse.constructor === Object) {
            return
        }
        if (Object.keys(apiResponse).length !== 0 && apiResponse.constructor === Object) {
            setAgeOptionsAvailable((apiResponse as SpeciesSelectionResponse).age)
            setGenderOptionsAvailable((apiResponse as SpeciesSelectionResponse).sex)
            setGeoRangeOptionsAvailable((apiResponse as SpeciesSelectionResponse).geo_range)
            setColorOptionsAvailable((apiResponse as SpeciesSelectionResponse).color_id)
            setBreedOptionsAvailable((apiResponse as SpeciesSelectionResponse).breed_id)
            setSpecies(speciesSelected)
        }
    }, [apiResponse])

Everything works as expected. I am just wondering if there is a more elegant/concise way of refactoring this.

2

I would say that you don’t need to wrap inputs in state.

Presumably the other state is displayed, and set by controls on this form. In that case it good to have states for each individually.

const SearchParams = ({ apiResponse, speciesSelected }: { apiResponse: SpeciesSelectionResponse| {}, speciesSelected: string }) => {

    const hasResponse = Object.keys(apiResponse).length !== 0 && apiResponse.constructor === Object

    const [desiredAge, setDesiredAge] = useState<string>("")
    const [desiredGender, setDesiredGender] = useState<string>("")
    const [desiredGeoRange, setDesiredGeoRange] = useState<string>("35")
    const [desiredColor, setDesiredColor] = useState<string>("")
    const [desiredBreed, setDesiredBreed] = useState<string>("")
    const [zipCode, setZipCode] = useState<string>("")
    const species = hasResponse ? speciesSelected : ""
    
    const ageOptionsAvailable = hasResponse ? apiResponse.age : []
    const genderOptionsAvailable = hasResponse ? apiResponse.sex : []
    const geoRangeOptionsAvailable = hasResponse ? apiResponse.geo_range : []
    const colorOptionsAvailable = hasResponse ? apiResponse.color_id : []
    const breedOptionsAvailable = hasResponse ? apiResponse.breed_id : []

    // etc
}
    

you can use useReducer for this kind of state

const reducer = (state: State, action: Action): State => {
  switch (action.type) {
    case 'SET_FIELD':
      return { ...state, [action.key]: action.value };
    default:
      return state;
  }
};

const Component = (initialState: State) => {
 const [state, dispatch] = useReducer(reducer, initialState);
 
 //example on change
 const onChange = ({key, value}: Action) => {
  dipstach({type: SET_FIELD, action: {key, value}   })
 }
 
 you can call it whenever you want
 onChange({
   key: "desiredAge",
   value: 1
 })

 ...rest of component body
}

//////////////
Fetch data here.

const hasResponse = Object.keys(apiResponse).length !== 0 && apiResponse.constructor === Object


//you dont need unecessary useffect in Component
...hasResponse ? <Component initialState={{
    desiredAge: apiResponse.desiredAge,
    desiredGender: apiResponse.desiredGender,
    ....REST OF API DATA
}} />
//////

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật