3

React 16.9

I am aware that this class component state:

class JustAnotherCounter extends Component {
  state = {
    count: 0
  };

is the equivalent of using Hooks useState:

function JustAnotherCounter() {
  const [count, setCount] = useState(0);

..but what would be the equivalent of the class component state below using Hooks useState?:

class Main extends Component {
    state = {
        step: 1,
        firstName: '',
        lastName: '',
        jobTitle: '',
        jobCompany: '',
        jobLocation: '',
    }

Any help would be much appreciated.

1

4 Answers 4

3

You can use the same general idea as in class components, just keep in mind that you'll need to spread the object yourself.

   const [state, setState] = useState({
        step: 1,
        firstName: '',
        lastName: '',
        jobTitle: '',
        jobCompany: '',
        jobLocation: '',
    });
   // Setting state like:
   setState(prev=>{...prev,firstName:'Joey'});

You can also set up multiple set state calls

const [step,setStep] = useState(1);
const [firstName,setFirstName] = useState('');
const [lastName,setLastName] = useState('');
const [jobTitle,setJobTitle] = useState('');
const [jobCompany,setJobCompany] = useState('');
const [jobLocation,setJobLocation] = useState('');

Another option is to use a reducer, which can be made into a far more complicated example than this:

const [state, dispatch] = useReducer(
  (state, action) => ({ ...state, [action.name]: action.value }),
  {
    step: 1,
    firstName: '',
    lastName: '',
    jobTitle: '',
    jobCompany: '',
    jobLocation: '',
  }
);
// Then update values using:
dispatch({ name: 'firstName', value: 'Joey' });

Sign up to request clarification or add additional context in comments.

Comments

2

You can useState to initalize objects like this:

function Main() {
  const [form, setValues] = useState({
      step: 1,
      firstName: '',
      lastName: '',
      jobTitle: '',
      jobCompany: '',
      jobLocation: '',
  })
}

And then to set the values you can do something like

setValues({
    ...form,
    firstName: 'Andrew',
})

Comments

1

Run { npm install react-multi-state } See how easy it is to use

import { Fragment } from 'react'
function Counter() {
  const [state, setState, { setCount }] = useMultiState({
    count: 0,
    secondCount: 10,
  })

  return (
    <Fragment>
      <button onClick={() => setCount(c => c + 1)}>Update count</button>

      <button
        onClick={() => {
          setState(prevState => ({
            secondCount: prevState.secondCount + 10,
            // use as many `prevState` property values as you wish
          }))
        }}
      >
        Update second count
      </button>
    </Fragment>
  )
}

You can easily update the states singly

https://github.com/whizkydee/react-multi-state/

Comments

1

You can save your state value as an object.

Remember when you update your object value using setState, you MUST create a new object instead of updating existing object's value, because setState compare object's reference value, not comparing the object value. This is different from using React Class component.

reference: https://reactjs.org/docs/hooks-faq.html#should-i-use-one-or-many-state-variables

save your state as an object

const [state, setState] = useState({ left: 0, top: 0, width: 100, height: 100 });
...
// deep clone your object (use other package like lodash or ramda for better performance)
const newObj = JSON.parse(JSON.stringify(state))
// update value and set state
newObj.top = 28
setState(state);

or using spreading for a single line setState

// Spreading "...state" ensures we don't "lose" width and height
setState(state => ({ ...state, left: e.pageX, top: e.pageY }));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.