Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does React setState() return?

I am using this.setState()inside of a ternary and trying to figure out what it returns. The documentation doesn't provide any information as to what it returns.

like image 603
Yuan Ting Deng Avatar asked Nov 29 '17 05:11

Yuan Ting Deng


People also ask

What does setState return in React?

Question: What Does React SetState() Return? React's SetState() Function That Lacks An Explicit Return Statement And Thus Will Return Undefined. If You Require A Return Value From SetState(), You Should Use The !!

What happens when you call setState ()?

Calling setState notifies the framework that the internal state of this object has changed in a way that might impact the user interface in this subtree, which causes the framework to schedule a build for this State object.

Does this setState return a promise?

setState uses callbacks and doesn't return a promise. Since this is rarely needed, creating a promise that is not used would result in overhead. In order to return a promise, setState can be promisified, as suggested in this answer.

Can we return setState?

setState() will always lead to a re-render unless shouldComponentUpdate() returns false . To avoid unnecessary renders, calling setState() only when the new state differs from the previous state makes sense and can avoid calling setState() in an infinite loop within certain lifecycle methods like componentDidUpdate .


2 Answers

As commented before,

I dont think it returns anything. Its a setter.

You can refer setState docs to understand what it does.

Now to answer your question, since react is closely associated with Typescript, following code is from the index.d.ts file of react. You can find the file here and you can check the definition here

setState<K extends keyof S>(f: (prevState: Readonly<S>, props: P) => Pick<S, K>, callback?: () => any): void;
setState<K extends keyof S>(state: Pick<S, K>, callback?: () => any): void;

As you see, both the definitions have same return type: void. This is because, first, it is a setter function. Second, on most occasion, setState will trigger a re-render. So you will not be able to do much.

If you have to do some processing after setState, you can pass a callback as second argument.

like image 69
Rajesh Avatar answered Sep 20 '22 19:09

Rajesh


React's setState() function that lacks an explicit return statement and thus will return undefined. If you require a return value from setState(), you should use the !! which will coerce it to return false. Hope that helps

like image 41
Gunther Avatar answered Sep 21 '22 19:09

Gunther