1. 程式人生 > >Understanding `static` in React

Understanding `static` in React

When I started learning React a couple years ago I started seeing static and began interacting with it more actively. Here’s an example:

Example of static properties in a React component.

Over time, static subconsciously worked it’s way into my development vocabulary, but I still didn’t know why I was using it. I would use it with defaultProps

, propTypes, contextTypes, and displayName, and I just assumed it needed to be there for some syntactic reason. I was following patterns that I saw on StackOverflow, and in docs without stopping to think about what static means.

Then I saw a neat example defining state without a constructor:

A React component with state and no constructor.

In previous examples I’d seen, state was always defined in the constructor of a class, so it caught my interest when I realized state could be defined without a constructor. I also noticed that state isn’t preceded by static which prompted the question: What the heck does static actually do?

And after a quick Google search, I had my answer…

Static properties are properties of a class, not of an instance of a class.

Let’s break that down a bit with an example.

If we have two instances of a React component Foo, the displayName, propTypes, defaultProps will remain the same across both instances, but the state of each instance will be able to update independently of one another.

thisFoo will have a state and thatFoo will have a state, but both share the same static properties — displayName, propTypes, and defaultProps— from the class definition.