React state depends on other state [closed]

Asked
Active3 hr before
Viewed126 times

6 Answers

closedstatereact
90%

Yes, setState is asynchronous, so this.state won't be updated immediately. Here are the unit tests for batching, which might explain some of the details., Jobs Programming & related technical career opportunities , Why is China interested in supporting the Taliban?

However this won't work for me, as my component actually has its own update loop which needs to check and possibly update its state at every tick. Since we cannot count on this.state to have been updated at every tick, I created a workaround that wraps React.createClass and adds it's own internal state tracking. (Requires jQuery for $.extend) (Fiddle: http://jsfiddle.net/kb3gN/4448/)

var Utils = new function() {
   this.createClass = function(object) {
      return React.createClass(
         $.extend(
            object, {
               _state: object.getInitialState ? object.getInitialState() : {},
               _setState: function(newState) {
                  $.extend(this._state, newState);
                  this.setState(newState);
               }
            }
         )
      );
   }
}
load more v
88%

Often, several components need to reflect the same changing data. We recommend lifting the shared state up to their closest common ancestor. Let’s see how this works in action.,For example, if we enter 37 into the Celsius input, the state of the Calculator component will be:,Currently, both TemperatureInput components independently keep their values in the local state:

function BoilingVerdict(props) {
  if (props.celsius >= 100) {
    return <p>The water would boil.</p>;  }
  return <p>The water would not boil.</p>;}
load more v
72%

Hooks ease the management of state and side effects inside functional React components. Moreover, repeated logic can be extracted into a custom hook to reuse across the application.,Proper management of hooks dependencies is an efficient way to solve the stale closure problem.,Inside the component <WatchCount> the hook useEffect() logs every 2 seconds the value of count:

function createIncrement(incBy) {
   let value = 0;

   function increment() {
      value += incBy;
      console.log(value);
   }

   const message = `Current value is ${value}`;

   function log() {
      console.log(message);
   }
   return [increment, log];
}

const [increment, log] = createIncrement(1);
increment(); // logs 1
increment(); // logs 2
increment(); // logs 3
// Does not work!
log(); // logs "Current value is 0"
load more v
65%

In the example below, we’re updating the variable dogNeedsVaccination independently of the other state variables.,The merging is shallow, so this.setState({ dogNeedsVaccination: true }) leaves the other variables intact, replacing only the value of dogNeedsVaccination.,This is the correct way of changing the state of variables that depend on the previous state.

Pretag
 Pretag team - issue, fix, solve, resolve
75%

Here’s why it works. When the asynchronous callback function is defined inside setTimeout, it saves a reference to the variables it uses, which is count in this case. This way, when the state updates, React not only changes the value but the variable reference in memory is completely different as well. ,Here’s why it works. When the asynchronous callback function is defined inside setTimeout, it saves a reference to the variables it uses, which is count in this case. This way, when the state updates, React not only changes the value but the variable reference in memory is completely different as well.,We are going to make this more scalable by giving ref the value of the state automatically when the state changes.

e.g.

const [count, setCount] = useState(0);
const ref = useRef(count);

useEffect(() => {
   ref.current = count
}, [count])
load more v
40%

Do I have to put all my state into Redux? Should I ever use React's setState()?Further information,Do I have to put all my state into Redux? Should I ever use React's setState()?,Can I put functions, promises, or other non-serializable items in my store state?

Pretag
 Pretag team - issue, fix, solve, resolve

Other "closed-state" queries related to "React state depends on other state [closed]"