user14487566
user14487566

Reputation:

React- is useState synchronous (not the setter returned by useState but useState itself)?

const Child = (props) =>
{
    const {data1, data2} = props;
    let defaultData = [];
    //do some logic based on data1 and data2 e.g.
    defaultData.push(data1 + data2); 
    const [myStateData, myStateDataSetter] = useState(defaultData);
    console.log(myStateData);
}

Will myStateData always be defined? (I understand that myStateDataSetter(newData) is async - that is not my question; I am asking if the first assignment using the default param to useState is synchronous).

Upvotes: 0

Views: 46

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371019

Yes it is. Given

const [someState, setSomeState] = useState(initialValue);

When the component mounts, someState will always be initialValue - it won't be undefined or anything else that requires a re-render before the state gets initially populated.

Upvotes: 0

Related Questions