In this article I will share how to use types and hooks in react-typescript app build
I. Use type with useState
useState is definitely a daily hook for each react dev , useState allows us to initialize and manage state inside function component similar to this.state in class component , following is a simple example using useState to declare a state with typescript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <span class="token keyword">import</span> React <span class="token keyword">from</span> <span class="token string">'react'</span> <span class="token keyword">const</span> App <span class="token operator">:</span> React <span class="token punctuation">.</span> <span class="token function-variable function">FC</span> <span class="token operator">=</span> <span class="token punctuation">(</span> <span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span> <span class="token keyword">const</span> <span class="token punctuation">[</span> inputValue <span class="token punctuation">,</span> setInputValue <span class="token punctuation">]</span> <span class="token operator">=</span> React <span class="token punctuation">.</span> useState <span class="token operator"><</span> string <span class="token operator">></span> <span class="token punctuation">(</span> <span class="token string">''</span> <span class="token punctuation">)</span> <span class="token keyword">return</span> <span class="token punctuation">(</span> <span class="token operator"><</span> div className <span class="token operator">=</span> <span class="token string">"main"</span> <span class="token operator">></span> <span class="token operator"><</span> input placeholder <span class="token operator">=</span> <span class="token string">"type something..."</span> value <span class="token operator">=</span> <span class="token punctuation">{</span> inputValue <span class="token punctuation">}</span> onChange <span class="token operator">=</span> <span class="token punctuation">{</span> <span class="token punctuation">(</span> <span class="token parameter">e</span> <span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token function">setInputValue</span> <span class="token punctuation">(</span> e <span class="token punctuation">.</span> target <span class="token punctuation">.</span> value <span class="token punctuation">)</span> <span class="token punctuation">}</span> <span class="token operator">/</span> <span class="token operator">></span> <span class="token operator"><</span> <span class="token operator">/</span> div <span class="token operator">></span> <span class="token punctuation">)</span> <span class="token punctuation">;</span> <span class="token punctuation">}</span> |
To specify a type for the state generated by useState , we specify the type with the syntax useState <type> (defaultValue) . Note that it is possible to specify a mixed type for state : useState <string | null> (null) .
II. Use type with useRef
Similar to createRef in classe component , useRef is a hook that creates an object that allows binding to DOM element inside function component . Specifying the type for the ref object using useRef is quite similar to the useState above, as can be seen from the following example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | import React from 'react' const App: React.FC = () => { const [inputValue, setInputValue] = React.useState<string>('') const mainRef = React.useRef<HTMLDivElement | null>(null) return ( <div ref={mainRef} className="main"> <input placeholder="type something..." value={inputValue} onChange={(e) => setInputValue(e.target.value)} /> </div> ); } |
III. Use type with useContext
useContext allows you to manipulate Context API more easily, if you have not learned about Context API , simply understand it is a React api that allows us to create states accessible by low components. without the effort of passing props and multiple levels of components , please refer here .
With typescript , we need to specify the type from the step that created the context
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | import React from 'react' interface User { name: string; age: number; } const UserContext = React.createContext<User[] || []>([]); const App: React.FC = () => { const userList = React.useState<User[] | []>([{ name: 'User 01', age: 15 }]) return ( <UserContext.Provider value={{ userList }}> <ChildComponent /> </UserContext.Provider> ) } |
Then specify the type in the step to access the data
1 2 3 4 5 6 7 8 9 10 11 | const ChildComponent: React.FC = () => { const { userList } = React.useContext<User[] | []>(UserContext) return ( <div> {userList.map(user => ( <UserItem user={user} /> ))} </div> ); } |
By the way above, we were able to handle the type for the state generated by the Context API .
III. Use type with useReducer
useReducer is an alternative to useState when we need to manage complex states , which is quite similar to state management with the redux library, perhaps hence the name reducer .
In order to use useReducer with typescript properly, we should note that specifying the type for action and state will be slightly different, assuming we have a simple state , but a count value and two actions allow us to. increase or decrease the count value, and do the following.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <span class="token keyword">import</span> React <span class="token keyword">from</span> <span class="token string">'react'</span> <span class="token keyword">enum</span> ActionTypes <span class="token punctuation">{</span> <span class="token constant">INCREMENT</span> <span class="token operator">=</span> <span class="token string">'INCREMENT'</span> <span class="token punctuation">,</span> <span class="token constant">DECREMENT</span> <span class="token operator">=</span> <span class="token string">'DECREMENT'</span> <span class="token punctuation">}</span> <span class="token keyword">interface</span> <span class="token class-name">TypeActions</span> <span class="token punctuation">{</span> type <span class="token operator">:</span> ActionTypes <span class="token punctuation">,</span> ue <span class="token operator">:</span> number <span class="token punctuation">,</span> <span class="token punctuation">}</span> <span class="token keyword">interface</span> <span class="token class-name">TypeState</span> <span class="token punctuation">{</span> count <span class="token operator">:</span> number <span class="token punctuation">;</span> <span class="token punctuation">}</span> <span class="token keyword">const</span> initialState <span class="token operator">:</span> TypeState <span class="token operator">=</span> <span class="token punctuation">{</span> count <span class="token operator">:</span> <span class="token number">0</span> <span class="token punctuation">}</span> |
We use interfaces to declare types for state, actions and use the Typescript enum – api that allows us to define a group of variable names that do not change, used to define the type cases that will have actions . After setup is complete, we just need to declare reducer :
1 2 3 4 5 6 7 8 9 10 11 | const reducer: React.Reducer<TypeState, TypeActions> = (state, action) => { switch (action.type) { case ActionTypes.INCREMENT: return { count: state.count + action.value }; case ActionTypes.DECREMENT: return { count: state.count - action.value }; default: return state; } }; |
Then use the newly created reducer inside the component :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | const App: React.FC = () => { const [state, dispatch] = React.useReducer<React.Reducer<TypeState, TypeActions>>( reducer, initialState ); return ( <div className="App"> <h1>Count: {state.count}</h1> <button onClick={() => dispatch({ type: ActionTypes.INCREMENT, value: countValue }) }> + </button> <button onClick={() => dispatch({ type: ActionTypes.DECREMENT, value: countValue }) }> - </button> </div> ); } |
Above I have just shared how to use typescript with some React Hooks , the article is referenced from the article The React TypeScript Cheatsheet – How To Set Up Types on Hooks , hope the information in this article will be useful. .