Home > OS >  How to use just 1 useState() for serveral states
How to use just 1 useState() for serveral states

Time:01-18

I have a react component that uses several states which are initialized in the same way useState(false), is there a way to combine all these states into a single useState(false)

  const [loading, setLoading] = useState(false);
  const [fields, setFields] = useState(false);
  const [wrongImageType, setWrongImageType] = useState(false);
  const [aboutError, setAboutError] = useState(false);
  const [destinationError, setDestinationError] = useState(false)

CodePudding user response:

You can do like this

const [states, setStates] = useState({ loading:false, fields:false, wrongImageType:false, aboutError:false, destinationError:false })

Update state like this

setStates((prevState) => ({ ...prevState, loading: true }))

CodePudding user response:

I usually use the useReducer hook. That way, I can just slam properties to some state object and the reducer tidies it all up for me. It also makes it easy when I have to submit an object to an API, I just fling the entire state object to the server. So it's basically, "fetch data from the server, use form inputs to let the user update the values, fling the data back to the server when they click the save button."

import React, {
  useReducer,
  useEffect
} from "react";

const initialState = {
  loading: false,
  fields: false,
  wrongImageType: false,
  aboutError: false,
  destinationError: false
};

const reducer = (prev, cur) => ({ ...prev, ...cur });

const MyComponent = () => {
  const [state, setState] = useReducer(reducer, initialState);

  useEffect(() => {
    setState({
      loading: true
    });

    // fetch something or do something...

    setState({
      loading: false
    });

  }, []);

  return ({
    state.loading ? <> Loading </> : <>{state.something}</>
  });
}

  •  Tags:  
  • Related