Home > OS >  React hooks useState initialization does not reset the state
React hooks useState initialization does not reset the state

Time:04-15

so I have a common component with a piece of state that should be initialized with a different value every time I visit another page. Right here I will be labeling my different pages as page A, and B.

in the component I have a initialization function to initialize the state such as below:

const stateInit = (inputArray) => {
  const initializedValue = {};
  // Do some condition logic to store initial value into the const variable

  // log to see the changes
  console.log("initializedValue: ", initializedValue);

  return initializedValue
}

in my functional component, I have declare the state as follow:

const [myState, setMyState] = useState<Object>(stateInit(props.inputArray));

// log to see the changes
console.log("myState: ", myState);

The inputArray will be different depending on which page of A, B I'm at.

This issue only occurs when I go between pages A <-> B

The expected behavior is when I switch between the two pages, the first console log will be the new value related to the page Im in, and the second console log has the state initialized with the new value related to the page.

The actual behavior is when I switch between the two pages, the first console log will be the new value related to the page Im in, but the second console log has the state with the previous initialized value.

I couldn't seem to figure out why the state is not initialized correctly. Does anyone have any clue about this?

CodePudding user response:

If the same instance of the functional component is used by both pages, then myState is initialized only once for all the pages and then the value is carried on between them. What might be misleading is that stateInit will be called every time there's a rerender but its value will be discarded apart from the time when the component is first instantiated. You might want to use lazy initial state:

useState<Object>(() => stateInit(props.inputArray))

to figure out when the component is actually created (stateInit will be called only then).

CodePudding user response:

Can you share your full code? this may be hapening because props.inputArray is getting undefined when changing from A->B, but i can't confirm without the rest of the code.

Best of Luck

  • Related