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.
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 !!
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.
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.
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 .
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With