Search code examples
reactjsreact-hooksreact-state-management

combining useState hook in a react component


I recently started using react hooks a lot.

State management seems more intuitive to me when using "React.useState".

Anyway, while it's working ok, I know it's starting to look cluttered the more values I am starting to save to state.

For example, as my car parts app has progressed, it is now looking like this:

const [isShown, setIsShown] = React.useState(false);
const [idVal, setIdValue] = React.useState(false);
const [partNameVal, setPartNameValue] = React.useState(false);
const [engineEngineEngineTypeVal, setEngineEngineTypeValue] = React.useState(false);
const [displacementVal, setDisplacementValue] = React.useState(false);
const [makeVal, setMakeValue] = React.useState(false);
const [countryVal, setCountryValue] = React.useState(false);

const hide = () => setIsShown(false);

const show = (id, partName, engineEngineType, displacement, department, country) => {
    setIsShown(true);
    setIdValue(id);
    setPartNameValue(partName);
    setEngineTypeValue(engineEngineType);
    setDisplacementValue(displacement);
    setMakeValue(department);
    setCountryValue(country);
}

<p>ID:  {idVal}</p>
<p>PartName:  {partNameVal}</p>
<p>EngineType:  {engineEngineTypeVal}</p>
<p>Displacement:  {displacementVal}</p>
<p>Make:  {makeVal}</p>
<p>Country:  {countryVal}</p>

I was wondering if there's a way to make this more readable, but still be very intuitive.

Thanks!


Solution

  • Typically you want to handle a single object or use useReducer, something like:

    const INITIAL_CAR = {
      id: 0,
      part: "4xE3",
      country: "USA",
      // ... More entries
    };
    
    const CarApp = () => {
      const [car, setCar] = useState(INITIAL_CAR);
      const [isShown, setIsShown] = useState(false);
    
      const show = (carProps) => {
        setIsShown(true);
        setCar(carProps);
      };
    
      const { id, part, engine, displacement, make, county } = car;
    
      const updateCountry = (country) =>
        setCar((prevCar) => ({ ...prevCar, country }));
    
      const updateCarProperty = ({ property, value }) =>
        setCar((prevCar) => ({ ...prevCar, [property]: value }));
    
      return (
        <div>
          {isShown && (
            <>
              <p>ID: {id}</p>
              <p>PartName: {part}</p>
              <p>EngineType: {engine}</p>
              <p>Displacement: {displacement}</p>
              <p>Make: {make}</p>
              <p>Country: {country}</p>{" "}
            </>
          )}
          // use show, updateCountry, updateProperty etc.
        </div>
      );
    };