Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Recommended way of importing React#518

filiptammergard started this conversation inGeneral
Discussion options

The first opinionated statement in the Basic Cheatsheet is thatthe most future proof way of importing React is using namespace import:

import*asReactfrom"react";

This might have been true a few years ago, but I think the widely spread recommended way nowadays is using destructured named imports, and only import what you need explicitly:

import{useState} from"react";

React Beta docs uses detructured named imports and I don't see why using TypeScript would make it different.

The announcement of the new JSX Transform that came with React 17 made it clear that destructured named imports is the preferred style going forward. Here's a quote of what the provided codemod does:

Change all default React imports (i.e.import React from "react") to destructured named imports (ex.import { useState } from "react") which is the preferred style going into the future. This codemod will not affect the existing namespace imports (i.e.import * as React from "react") which is also a valid style. The default imports will keep working in React 17, but in the longer term we encourage moving away from them.

Along where we say using namespace imports is the most future proof way in the Basic Cheatsheet, we're also saying this:

If you set--allowSyntheticDefaultImports (or add"allowSyntheticDefaultImports": true) in yourtsconfig.json you can use more familiar [default] imports.

Since default imports are not recommended, I'm not sure we even need to keep this at all. For many React developers, destructured named imports is becoming the new most familiar way of importing React. If not throwing it out completely, I think it should be reworked a bit and placed in<details>.

I'm happy to work on this according to my thoughts here, but I'd like to hear your thoughts as well first since I'm not sure if this is controversial. I'd also like to hear your opinion on direction. Should we:

  1. Remove the section about importing React completely? Aside from theallowSyntheticDefaultImports quirk needed to get default import of React working, there's not really anything special about importing React when using TypeScript compared to JavaScript. Why not let React's best practices apply and add something here if there is something TypeScript related to keep in mind in the area?
  2. Modify the section to recommend destructured named imports of React?
  3. Keep as is?

Let me know what you think. Particularly interested in your thoughts@eps1lon!

You must be logged in to vote

Replies: 2 comments 5 replies

Comment options

I'd keep it simple and do whateverhttps://beta.reactjs.org/ does.

Ideally we'd archive this cheatsheet and just link to the relevant sections on reactjs.org but it will take a while to upstream everything.

You must be logged in to vote
4 replies
@filiptammergard
Comment options

filiptammergardJun 10, 2022
Maintainer Author

Does that mean you'd go for removing the section about importing React in the cheatsheet in this case?

@eps1lon
Comment options

could you link that section? just to make sure there's nothing we should keep. But I wouldn't recommend an import style here. That's up to the library.

@filiptammergard
Comment options

filiptammergardJun 10, 2022
Maintainer Author

Ah sorry, here it is:https://react-typescript-cheatsheet.netlify.app/docs/basic/setup#import-react

@eps1lon
Comment options

Yeah that section can be removed. It's really annoying if that comes up in a discussion and one party links the official docs and the other party links this cheatsheet. We should just sync with the official docs. And if they still useimport React from 'react' we should update it (consideringfacebook/react#18102)

Comment options

1.When should you use TypeScript with React instead of just JavaScript?
✅ When your project is medium/large or will grow in complexity.
✅ When you want type safety to catch errors at compile time.
✅ When you work in a team or contribute to open source (for better code clarity).
✅ When you want better IDE support (auto-complete, refactoring).
2.How to declare styles for props in a React component?
You can type style props as React.CSSProperties:
type MyComponentProps = {
style?: React.CSSProperties;
};

const MyComponent: React.FC<MyComponentProps> = ({ style }) => (<div style={style}>Hello</div>);

3.What is the difference between interface and type in TypeScript? Which one to use for props?

Featureinterfacetype
ExtendableYes (can merge with other interfaces, declaration merging)No (but can intersect with&)
Suitable for props✅ Yes✅ Yes
Preferred?Often preferred for props because of easier extensionFine too, especially for unions & mapped types

4.How to define a functional component with TypeScript?
✅ The cleanest way:

interface Props {    title: string;}const MyComponent: React.FC<Props> = ({ title }) => {    return <h1>{title}</h1>;};
  1. How to declare types for useState, useReducer, useRef, useContext?
  • useState
    const [count, setCount] = useState(0);

  • useReducer
    type State = { count: number };
    type Action = { type: 'increment' | 'decrement' };

    const reducer = (state: State, action: Action): State => { /* logic */ };
    const [state, dispatch] = useReducer(reducer, { count: 0 });

6.How to style events in handlers like onClick, onChange, onSubmit...?

const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => { /* ... */ };    const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => { /* ... */ };    const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {    e.preventDefault();    // ...};

7.How to use TypeScript utility types like Partial, Pick, Record, Omit in React?
- Partial: Make all props optional
type PartialProps = Partial<{ title: string; age: number }>;
- Pick: Pick specific props
type PickedProps = Pick<{ title: string; age: number; name: string }, 'title' | 'name'>;
- Omit: Exclude certain props
type WithoutAge = Omit<{ title: string; age: number; name: string }, 'age'>;
- Record: Map keys to types
const styles: Record<string, React.CSSProperties> = {
header: { color: 'red' },
body: { fontSize: 14 }
};

You must be logged in to vote
1 reply
@honeyforce
Comment options

thanks, helpful

Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment
Category
General
Labels
BASICBasic Cheatsheet
3 participants
@filiptammergard@eps1lon@honeyforce

[8]ページ先頭

©2009-2025 Movatter.jp