React Hooks y Typescript

Guía para integrar los hooks básicos de React con Typescript

El hook useState

const [count, setCount] = useState(0);
const [myNumber, myNumberSet] = useState<number>(0);
const [user, setUser] = useState(null);
interface User {
id: number;
email: string;
}
const [user, setUser] = useState<User | null>(null);
interface User {
id: number;
email: string;
}
const [users, setUsers] = useState<User[]>([]);

El hook useReducer

type Actions = 
| { type: "SET; payload: number; }
| { type: "INCREMENT; payload: number; }
| { type: "DECREMENT"; payload: number; };
type State = { count: number; }const initialState = {
count: 0,
};
function countReducer(
state: State,
action: Actions
) {
...}
const [state, dispatch] = useReducer(countReducer, initialState);// state : State✅ dispatch({type: "SET, payload: 10});❌ dispatch({type: "RANDOM, payload: 10});

El hook useRef

// Es lo mismoconst count = useRef(0);
const count = useRef<number>(0);

// Tipando useRef
interface User {
id: number;
email: string;
}
const user = useRef<User | null>(null);
const divRef = useRef<HTMLDivElement | null>(null);

El hook useCallback

type FormValues = {
name: string;
}
const prepareValues = useCallback(
function(formValues: FormValues) {
return { ...formValues, id: generateRandomId() };
},
[]
);
// prepareValues: FormValues => { name: string, id: string };
type FormValues = {
name: string;
}
type ApiValues = {
id: string;
name: string;
}
const prepareValues = useCallback(
function(formValues: FormValues): ApiValues {
return { ...formValues, id: generateRandomId() };
},
[]
);
// prepareValues: FormValues => ApiValues};

El hook useMemo

const people = ['Gerardo', 'Andrea', 'Francisco'];const peopleInLowerCase = useMemo(
() => people.map(name => name.toUpperCase()),
[people]
);
// peopleInLowerCase: string[]
type Name = string;const people = ['Gerardo', 'Andrea', 'Francisco'];const peopleInLowerCase: = useMemo<Name[]>(
() => people.map(name => name.toUpperCase()),
[people]
);
// peopleInLowerCase: Name[]

El hook useContext

// 😢 const TokenContext = createContext(null);const context = useContext(TokenContext);
// 😊interface TokenContextState {
token: string;
}
const TokenContext = createContext<TokenContextState | null>(null);const context = useContext(TokenContext);// context: TokenContextState | nul
// 😊const TokenContext = createContext({
token: ''
});
const context = useContext(TokenContext);// context: {token: string}

El hook useEffect

Conclusiones

¿Quieres recibir más artículos como este?

Entre paseo y paseo con Simba desarrollo en Symfony y React

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store