DEV Community

Cover image for Taking React and Redux to the next level with Typescript

Taking React and Redux to the next level with Typescript

Leo Melo on September 02, 2019

Prologue If you ever used Redux before you know that much of the ways we write Redux logic and why it works relies on us knowing the sha...
Collapse
 
jlarky profile image
JLarky

I can recommend also checking out some other ways to implement type safe redux medium.com/@dhruvrajvanshi/some-ti... and gist.github.com/JLarky/93d6b5c87a7...

as for TMoviesListProps example with hooks you can actually do pretty cool stuff

import { TypedUseSelectorHook, useDispatch as useDispatchGeneric, useSelector as useSelectorGeneric } from "react-redux";

export const useSelector: TypedUseSelectorHook<AppState> = useSelectorGeneric;
export const useDispatch: () => Dispatch<Action> = useDispatchGeneric;

function useRedux() {
    const movies = useSelector(state => state.movies.movies);
    const isLoaded = useSelector(state => state.movies.moviesLoaded);
    const moviesLoadedAt = useSelector(state => state.movies.moviesLoadedAt);
    const dispatch = useDispatch();
    return {
        movies,
        isLoaded,
        moviesLoadedAt,
        dispatch,
    };
}

type TMoviesListProps = ReturnType<typeof useRedux>;

export default function MoviesListContainer() {
    const props = useRedux();
    return <MoviesList {...props} />;
}
Collapse
 
leomeloxp profile image
Leo Melo

Thanks for sharing this, I haven't got to using Redux with hooks yet... That was gonna be my next step with that code base, converting it all to hooks.

I might post a follow up to this with some hooks code once I get around to it.

Collapse
 
jlarky profile image
JLarky

I like that hooks and custom hooks allow you to easily make sure that your react component is typed. Compare const [value] = React.useState("") which clearly has value typed as string with all that duplicated code to properly add state to the component. I'm not converting all of my code base to hooks just yet :) but first thing that I'm going to convert is probably going to be all that react-redux connect code :)

Collapse
 
jjplusplus profile image
Jj Medina

So, keeping in mind that I'm brand new to TypeScript, I don't think it was clear where you got the Dispatch from in the line const mapDispatchToProps = (dispatch: Dispatch<AnyAction>) =>

Collapse
 
wolverineks profile image
Kevin Sullivan

import { Dispatch} from redux
More cool stuff github.com/piotrwitek/react-redux-...

Collapse
 
johanneslichtenberger profile image
Johannes Lichtenberger

Hmm, I'm just thinking that it probably would be great to persist the application states and be able to restore the full history sometimes :-)