Search code examples
javascriptreactjsfrontendcomponentsstate

React functional component access entire state


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.


Solution

  • 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.