0

In a classical component the entire state is available as a single object this.state = {}, I was wondering if there's a similar way you could access the state in a functional component? You can access individual properties via their variable names but I'm wondering if there's a way to access all of them at once as if they were stored in an overarching object, similar to a class component.

1 Answer 1

2

No, there's no consolidated state object you can get access to that has all of the state members you've set up via useState.

You could store all of your component state in a single object if you want (this is even mentioned in the useState docs when talking about callback updates). For instance:

const [state, setState] = useState({
    name: "",
    profession: "",
    age: null,
    // ...
});

To update any individual state member, you have to handle creating the entire new object yourself (state setters from useState don't do the merging that Component.prototype.setState does). For instance, setting the age:

setState(state => ({
    ...state,
    age: 42,
}));

It's important to use the callback form (as is always the case when setting state based on existing state).

But unless you do that, no, there's no one single object you have access to.

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

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.