Skip to content Skip to sidebar Skip to footer

How To Update Value Returned By Function React (usestate Implementation)

Let's say I have such a thing, function returning value and setter Function, how Can I implement the setter function correctly to update returned value , every time it is called? (

Solution 1:

If you're trying to re-implement how React does it, you would have to have setter functions result in the whole block running again - something like the following:

const state = [];
constApp = () => {
  let stateIndex = 0; // This variable keeps track of the sequential calls to `myFunction`// (Needed if myFunction gets called multiple times)constmyFunction = (initialValue) => {
    // Assign initial value if it doesn't exist yetif (!state.hasOwnProperty(stateIndex)) state[stateIndex] = initialValue;
    const value = state[stateIndex];
    // Need to create a closure over the current state index...const closureStateIndex = stateIndex;
    constsetterFunction = (newValue) => {
      state[closureStateIndex] = newValue;
      // Re-run the entire function asynchronously:setTimeout(App);
    };
    // Increment state index to allow for additional calls to myFunction
    stateIndex++;
    return [value, setterFunction];
  }
  const [myValue, updaterFunc] = myFunction('initialValue');
  // Call updater only on initial render:if (myValue === 'initialValue') {
    updaterFunc('newValue'); // myValue's new Value should be 'newValue'
  }
  console.log('Rendering. Current value is:', myValue);
};

App();

That's a bit similar to how React does it.

For an example with multiple state variables, and renaming myFunction to useState:

const state = [];
constApp = () => {
  let stateIndex = 0;
  constuseState = (initialValue) => {
    if (!state.hasOwnProperty(stateIndex)) state[stateIndex] = initialValue;
    const value = state[stateIndex];
    const closureStateIndex = stateIndex;
    constsetterFunction = (newValue) => {
      state[closureStateIndex] = newValue;
      setTimeout(App);
    };
    stateIndex++;
    return [value, setterFunction];
  }
  const [name, setName] = useState('bob');
  const [age, setAge] = useState(5);
  if (age === 5) {
    setAge(10);
  }
  console.log('Rendering. Current name and age is:', name, age);
};

App();

Post a Comment for "How To Update Value Returned By Function React (usestate Implementation)"