Typescript and React
Page content
1. Hello, world
1.1 Create a React App
yarn create react-app <appName> --template typescript
1.2 Start the React App
yarn start
2. React hooks with TypeScript
2.1 useState
-
Typescript (TS)can infer the type of certain variables based on initialisation if a lack of explicit information. -
If the state is immediately initialised upon declaration, you do not need to make any changes.
const [count, setCount] = useState(0); // It infers that 0 is a number.
null,undefinedor some object with incomplete data type cause an error.
const [state, setState] = useState(); // error
const [state, setState] = useState(null); // error
const [state, setState] = useState({
state: '', // if secondState defined in setState({ state: '', secondState: ''});
})
type User = {
email: string;
username?: string;
}; // Now it works.
const [user, setUser] = useState<User>({
email: "",
});
// Array
const [users, setUsers] = useState<User[]>([]);
// OR
const [users, setUsers] = useState<Array<User>>([]);
2.2 useEffect
TSwill not allow you to return anything other than a function orundefinedforuseEffect.
2.3 useReducer
TSwill infer the return type of reducer if you do not define it.
2.4 useRef
- In
TS,useRefreturns a reference that is eitherreadonlyormutable. It depends on whether your type argument fully covers the initial value or not.- To access a DOM element: provide only the element type as argument, and use
nullas initial value. It will returnreadonly. - To have a mutable value: provide the type you want, and make sure the initial value fully belongs to that type.
- To access a DOM element: provide only the element type as argument, and use
2.5 useCallback
TSknows thatuseCallbackaccepts a function and an array of dependencies.
3. React.ReactNode
- A
ReactNodeis one of the following types:booleannullorundefinednumberstring- A React element (result of JSX)
- An array of any of the above, possibly a nested one.
4. children parameter
- It describes what child elements have, if any.
- A child element could be any ReactNode.