What Is Usestate() in React

What is useState() in React?

React hooks are a new way (still being developed) to access the core features of react such as state without having to use classes, in your example if you want to increment a counter directly in the handler function without specifying it directly in the onClick prop, you could do something like:

...
const [count, setCounter] = useState(0);
const [moreStuff, setMoreStuff] = useState(...);
...

const setCount = () => {
setCounter(count + 1);
setMoreStuff(...);
...
};

and onClick:

<button onClick={setCount}>
Click me
</button>

Let's quickly explain what is going on in this line:

const [count, setCounter] = useState(0);

useState(0) returns a tuple where the first parameter count is the current state of the counter and setCounter is the method that will allow us to update the counter's state. We can use the setCounter method to update the state of count anywhere - In this case we are using it inside of the setCount function where we can do more things; the idea with hooks is that we are able to keep our code more functional and avoid class based components if not desired/needed.

I wrote a complete article about hooks with multiple examples (including counters) such as this codepen, I made use of useState, useEffect, useContext, and custom hooks. I could get into more details about how hooks work on this answer but the documentation does a very good job explaining the state hook and other hooks in detail.

update: Hooks are not longer a proposal, since version 16.8 they're now available to be used, there is a section in React's site that answers some of the FAQ.

React JS Constructor vs useState what's the difference?

Generally, these are two different approaches in React. The constructor type is part of the OOP React approach with the so called class components. There you have class methods instead of functions. And the state is accessed through this.state.<property>.

The other approach is the function components. That's the more modern way of doing stuff with React. useState() is a React hook, responsible for a particular state.

They work the same, however the function-based approach is getting more and more common, so I would suggest to switch to function components, unless something requires the explicit usage of class components.

How to add if condition inside of useState in React

you can initialize state lazily

const [buttonName, setButtonName] = useState(() => {
return localStorage.getItem('address') ? 'Wallet Connected' : 'Connect Wallet'
});

React useState - update all object values to true

The problem you are facing is that you are mutating the state object, which means that at the end, prevState === nextState and React bails out of rendering. An option is to use a new object and copy the props like this, using the same combo of Object.keys and forEach but adding an extra step:

setState(prevState => {
const nextState = {}
Object.keys(prevState).forEach(key => {
nextState[key] = true
})
return nextState
})

React useState() hook returns undefined when using option chained value as initial count

I fixed it using useEffect(). Maybe the setCarQuantity() was failed to set the value immediately and after using useEffect() it listens to the state change.

const [carQuantity, setCarQuantity] = useState(totalQuantity);
useEffect(() => {
setCarQuantity(totalQuantity);
}, [totalQuantity]);

ReactJS useState hook: Can I update array of objects using the state variable itself?

Both implementations would be considered state mutations and should be avoided as this is anti-pattern in React. React uses shallow reference equality checks as part of its Reconciliation process, i.e. if a chunk of state is the same object reference as the previous render cycle it's assumed the value is the same and rerendering is skipped.

  • Version 1

    This is just directly mutating the state object.

      list[index][someKey] = some_updated_value; // <-- mutation!
    setList(list);
  • Version 2

    This also directly mutates the state object since newList is a reference to list.

      const newList = list; // <-- newList reference to state
    newList[index][someKey] = some_updated_value; // <-- mutation!
    setList(newList);

The idea with React state updates is to apply the Immutable Update Pattern. This is where you create shallow copies of any state and nested state that is being updated. This is also usually combined with functional state updates where you pass a callback function to the updater function that is passed the previous state to update from. This helps avoid stale state enclosures.

Example:

setList(list => list.map((item, i) => // Array.protptype.map creates new array
i === index
? { // new object reference for updated item
...item, // shallow copy previous item state
[someKey]: newValue // overwrite property being updated
}
: item
));

Good docs:

  • Immutable Update Pattern - this is a Redux doc but provides a fantastic explanation and example.
  • Functional State Updates


Related Topics



Leave a reply



Submit