This is one stop global knowledge base where you can learn about all the products, solutions and support features.
setState
do?
setState()
schedules an update to a component’s
state
object. When state changes, the component responds by re-rendering.
state
and
props
?
props
(short for “properties”) and
state
are both plain JavaScript objects. While both hold information that influences the output of render, they are different in one important way:
props
get passed
to
the component (similar to function parameters) whereas
state
is managed
within
the component (similar to variables declared within a function).
Here are some good resources for further reading on when to use
props
vs
state
:
setState
giving me the wrong value?
In React, both
this.props
and
this.state
represent the
rendered
values, i.e. what’s currently on the screen.
Calls to
setState
are asynchronous - don’t rely on
this.state
to reflect the new value immediately after calling
setState
. Pass an updater function instead of an object if you need to compute values based on the current state (see below for details).
Example of code that will not behave as expected:
incrementCount() {
// Note: this will *not* work as intended.
this.setState({count: this.state.count + 1});
}
handleSomething() {
// Let's say `this.state.count` starts at 0.
this.incrementCount();
this.incrementCount();
this.incrementCount();
// When React re-renders the component, `this.state.count` will be 1, but you expected 3.
// This is because `incrementCount()` function above reads from `this.state.count`,
// but React doesn't update `this.state.count` until the component is re-rendered.
// So `incrementCount()` ends up reading `this.state.count` as 0 every time, and sets it to 1.
// The fix is described below!
}
See below for how to fix this problem.
Pass a function instead of an object to
setState
to ensure the call always uses the most updated version of state (see below).
setState
?
Passing an update function allows you to access the current state value inside the updater. Since
setState
calls are batched, this lets you chain updates and ensure they build on top of each other instead of conflicting:
incrementCount() {
this.setState((state) => {
// Important: read `state` instead of `this.state` when updating.
return {count: state.count + 1}
});
}
handleSomething() {
// Let's say `this.state.count` starts at 0.
this.incrementCount();
this.incrementCount();
this.incrementCount();
// If you read `this.state.count` now, it would still be 0.
// But when React re-renders the component, it will be 3.
}
Learn more about setState
setState
asynchronous?
Currently,
setState
is asynchronous inside event handlers.
This ensures, for example, that if both
Parent
and
Child
call
setState
during a click event,
Child
isn’t re-rendered twice. Instead, React “flushes” the state updates at the end of the browser event. This results in significant performance improvements in larger apps.
This is an implementation detail so avoid relying on it directly. In the future versions, React will batch updates by default in more cases.
this.state
synchronously?
As explained in the previous section, React intentionally “waits” until all components call
setState()
in their event handlers before starting to re-render. This boosts performance by avoiding unnecessary re-renders.
However, you might still be wondering why React doesn’t just update
this.state
immediately without re-rendering.
There are two main reasons:
props
and
state
, causing issues that are very hard to debug.
This GitHub comment dives deep into the specific examples.
Maybe.
It’s a good idea to get to know React first, before adding in additional libraries. You can build quite complex applications using only React.
Pass a string as the
className
prop:
render() {
return <span className="menu navigation-menu">Menu</span>
}
It is common for CSS classes to depend on the component props or state:
render() {
let className = 'menu';
if (this.props.isActive) {
className += ' menu-active';
}
return <span className={className}>Menu</span>
}
Tip
If you often find yourself writing code like this, classnames package can simplify it.
Yes, see the docs on styling here.
CSS classes are generally better for performance than inline styles.
“CSS-in-JS” refers to a pattern where CSS is composed using JavaScript instead of defined in external files.
Note that this functionality is not a part of React, but provided by third-party libraries.
React does not have an opinion about how styles are defined; if in doubt, a good starting point is to define your styles in a separate
*.css
file as usual and refer to them using
className
.
React can be used to power animations. See React Transition Group, React Motion, React Spring, or Framer Motion, for example.
React doesn’t have opinions on how you put files into folders. That said there are a few common approaches popular in the ecosystem you may want to consider.
One common way to structure projects is to locate CSS, JS, and tests together inside folders grouped by feature or route.
common/
Avatar.js
Avatar.css
APIUtils.js
APIUtils.test.js
feed/
index.js
Feed.js
Feed.css
FeedStory.js
FeedStory.test.js
FeedAPI.js
profile/
index.js
Profile.js
ProfileHeader.js
ProfileHeader.css
ProfileAPI.js
The definition of a “feature” is not universal, and it is up to you to choose the granularity. If you can’t come up with a list of top-level folders, you can ask the users of your product what major parts it consists of, and use their mental model as a blueprint.
Another popular way to structure projects is to group similar files together, for example:
api/
APIUtils.js
APIUtils.test.js
ProfileAPI.js
UserAPI.js
components/
Avatar.js
Avatar.css
Feed.js
Feed.css
FeedStory.js
FeedStory.test.js
Profile.js
ProfileHeader.js
ProfileHeader.css
Some people also prefer to go further, and separate components into different folders depending on their role in the application. For example, Atomic Design is a design methodology built on this principle. Remember that it’s often more productive to treat such methodologies as helpful examples rather than strict rules to follow.
There are many pain points associated with deep directory nesting in JavaScript projects. It becomes harder to write relative imports between them, or to update those imports when the files are moved. Unless you have a very compelling reason to use a deep folder structure, consider limiting yourself to a maximum of three or four nested folders within a single project. Of course, this is only a recommendation, and it may not be relevant to your project.
If you’re just starting a project, don’t spend more than five minutes on choosing a file structure. Pick any of the above approaches (or come up with your own) and start writing code! You’ll likely want to rethink it anyway after you’ve written some real code.
If you feel completely stuck, start by keeping all files in a single folder. Eventually it will grow large enough that you will want to separate some files from the rest. By that time you’ll have enough knowledge to tell which files you edit together most often. In general, it is a good idea to keep files that often change together close to each other. This principle is called “colocation”.
As projects grow larger, they often use a mix of both of the above approaches in practice. So choosing the “right” one in the beginning isn’t very important.
React follows semantic versioning (semver) principles.
That means that with a version number x.y.z :
Major releases can also contain new features, and any release can include bug fixes.
Minor releases are the most common type of release.
This versioning policy does not apply to prerelease builds in the Next or Experimental channels. Learn more about prereleases.
Breaking changes are inconvenient for everyone, so we try to minimize the number of major releases – for example, React 15 was released in April 2016 and React 16 was released in September 2017, and React 17 was released in October 2020.
Instead, we release new features in minor versions. That means that minor releases are often more interesting and compelling than majors, despite their unassuming name.
As we change React over time, we try to minimize the effort required to take advantage of new features. When possible, we’ll keep an older API working, even if that means putting it in a separate package. For example, mixins have been discouraged for years but they’re supported to this day via create-react-class and many codebases continue to use them in stable, legacy code.
Over a million developers use React, collectively maintaining millions of components. The Facebook codebase alone has over 50,000 React components. That means we need to make it as easy as possible to upgrade to new versions of React; if we make large changes without a migration path, people will be stuck on old versions. We test these upgrade paths on Facebook itself – if our team of less than 10 people can update 50,000+ components alone, we hope the upgrade will be manageable for anyone using React. In many cases, we write automated scripts to upgrade component syntax, which we then include in the open-source release for everyone to use.
Development builds of React include many helpful warnings. Whenever possible, we add warnings in preparation for future breaking changes. That way, if your app has no warnings on the latest release, it will be compatible with the next major release. This allows you to upgrade your apps one component at a time.
Development warnings won’t affect the runtime behavior of your app. That way, you can feel confident that your app will behave the same way between the development and production builds — the only differences are that the production build won’t log the warnings and that it is more efficient. (If you ever notice otherwise, please file an issue.)
In general, we don’t bump the major version number for changes to:
unstable_
.
These are provided as experimental features whose APIs we are not yet confident in. By releasing these with an
unstable_
prefix, we can iterate faster and get to a stable API sooner.
__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED
or
__reactInternalInstance$uk43rzhitjg
, there is no warranty. You are on your own.
This policy is designed to be pragmatic: certainly, we don’t want to cause headaches for you. If we bumped the major version for all of these changes, we would end up releasing more major versions and ultimately causing more versioning pain for the community. It would also mean that we can’t make progress in improving React as fast as we’d like.
That said, if we expect that a change on this list will cause broad problems in the community, we will still do our best to provide a gradual migration path.
It’s possible that a minor release will not include new features. This is allowed by semver, which states ”[a minor version] MAY be incremented if substantial new functionality or improvements are introduced within the private code. It MAY include patch level changes.”
However, it does raise the question of why these releases aren’t versioned as patches instead.
The answer is that any change to React (or other software) carries some risk of breaking in unexpected ways. Imagine a scenario where a patch release that fixes one bug accidentally introduces a different bug. This would not only be disruptive to developers, but also harm their confidence in future patch releases. It’s especially regrettable if the original fix is for a bug that is rarely encountered in practice.
We have a pretty good track record for keeping React releases free of bugs, but patch releases have an even higher bar for reliability because most developers assume they can be adopted without adverse consequences.
For these reasons, we reserve patch releases only for the most critical bugs and security vulnerabilities.
If a release includes non-essential changes — such as internal refactors, changes to implementation details, performance improvements, or minor bugfixes — we will bump the minor version even when there are no new features.
The virtual DOM (VDOM) is a programming concept where an ideal, or “virtual”, representation of a UI is kept in memory and synced with the “real” DOM by a library such as ReactDOM. This process is called reconciliation.
This approach enables the declarative API of React: You tell React what state you want the UI to be in, and it makes sure the DOM matches that state. This abstracts out the attribute manipulation, event handling, and manual DOM updating that you would otherwise have to use to build your app.
Since “virtual DOM” is more of a pattern than a specific technology, people sometimes say it to mean different things. In React world, the term “virtual DOM” is usually associated with React elements since they are the objects representing the user interface. React, however, also uses internal objects called “fibers” to hold additional information about the component tree. They may also be considered a part of “virtual DOM” implementation in React.
No, they are different. The Shadow DOM is a browser technology designed primarily for scoping variables and CSS in web components. The virtual DOM is a concept implemented by libraries in JavaScript on top of browser APIs.
Fiber is the new reconciliation engine in React 16. Its main goal is to enable incremental rendering of the virtual DOM. Read more.