mirror of
https://github.com/facebook/react.git
synced 2025-11-01 09:12:30 +00:00
db40a5b15f
This validation ensures that React compiler-enabled apps remain correct. That is, code that errors with this validation is most likely ***invalid*** with React compiler is enabled (specifically, hook calls will be compiled to if-else memo blocks).
Hook guards are used extensively for Meta's react compiler rollouts. There, they're enabled for developers (for dev builds) and on e2e test runs. Let's enable by default for oss as well
### Examples of inputs this rule throws on
* Components should not be invoked directly as React Compiler could memoize the call to AnotherComponent, which introduces conditional hook calls in its compiled output.
```js
function Invalid1(props) {
const myJsx = AnotherComponent(props);
return <div> { myJsx } </div>;
}
```
* Hooks must be named as hooks. Similarly, hook calls may not appear in functions that are not components or hooks.
```js
const renamedHook = useState;
function Invalid2() {
const [state, setState] = renamedHook(0);
}
function Invalid3() {
const myFunc = () => useContext(...);
myFunc();
}
```
* Hooks must be directly called (from the body of a component or hook)
```
function call(fn) {
return fn();
}
function Invalid4() {
const result = call(useMyHook);
}
```
### Example of hook guard error (in dev build)
<img width="1237" alt="image" src="https://github.com/user-attachments/assets/e9ada403-b0d7-4840-b6d5-ad600519c6e6" />
babel-plugin-react-compiler
React Compiler is a compiler that optimizes React applications, ensuring that only the minimal parts of components and hooks will re-render when state changes. The compiler also validates that components and hooks follow the Rules of React.
This package contains the React Compiler Babel plugin use in projects that make use of Babel. You can find instructions for using this plugin here: https://react.dev/learn/react-compiler