React Style Guide
React Style Guide
[ React import ] [ Exports ] [ Functions ] [ Event handler functions naming ] [ Event handler props naming ] [ Ternary operator ]
React import
Import from the React package. Do not import React itself.
1 /* Bad */
8 React.useEffect(() => {
9 ...
10 });
11 };
12
13 /* Good */
15
19
20 useEffect(() => {
21 ...
22 });
23 };
Exports
Prefer to use named export in favor of the default one.
1 /* Bad */
4 /* Good */
This guidance will be revisited in the new conventions / architecture. Continue using this in app/ base source code.
Functions
Use arrow function in favor of function declaration.
1 /* Bad */
4 }
6 /* Good */
9 };
1 handle[subject?][event]
Example:
1 /* Bad */
6 /* Good */
This guidance still holds true for the new src base. The extra requirement will be to always memoize the callbacks with
useCallback()
1 on[subject?][event]
When creating a React component which has a prop that handles something, simply follow the onEvent convention (adding a Subject if
applicable):
1 /* Bad */
2 <SomeComponent handleFormSubmit={handleFormSubmit}></SomeComponent>
3 <SomeComponent submit={handleFormSubmit}></SomeComponent>
5 /* Good */
6 <SomeComponent
7 onFormSubmit={handleFormSubmit}
8 onFormReset={handleFormReset}
9 ></SomeComponent>
10 <SomeComponent onSubmit={handleFormSubmit}></SomeComponent>
Ternary operator
Try to use ternary operator only for the simplest cases:
1 /* Good */
1 /* Bad */
2 {
3 isSomeFeatureEnabled ? (
4 <>
5 {!isLoading ? (
6 <>
7 {Boolean(items.length)? (
8 <>
9 <ComponentOne />
10 <ComponentTwo />
11 </>
12 ) : (
13 <ComponentThree />
14 )}
15 </>
16 ) : (
17 <Spinner />
18 )}
19 </>
20 ) : (
21 <Placeholder />
22 );
23 }