What is the useReducer Hook?

Photo by Berkay Gumustekin on Unsplash

‘Hooks are functions that let you “hook into” React state and lifecycle features from function component. They do not work within a class. They let you use React without a class.’ — React Official Blog post.

What is a Reducer?

I like to think of a Reducer in Redux as a “Coffee Maker”. It takes in an old state and action and brews a new state (Fresh coffee).

Given a set of inputs, it should always return the same output. No surprises, side effects, API calls, mutations.

What is the useReducer Hook?

const [state, dispatch] = useReducer(reducer, initialArg, init);

How to use the useReducer Hook?

import React, { useReducer } from "react";
const initialState = { react: false, graphQL: false, angular: false };
const Courses = () => {
const [state, dispatch] = useReducer(counterReducer, initialState);
const handleReactPress = () => {
dispatch({ type: "REACT" });
};
const handleGraphQLPress = () => {
dispatch({ type: "GRAPHQL" });
};
const handleAngularPress = () => {
dispatch({ type: "ANGULAR" });
};
return (
<div className="box">
<h2>Use Reducer Example Component</h2>
<p>
Learning{" "}
{state.react
? "React"
: state.graphQL
? "GraphQL"
: state.angular
? "Angular"
: "Not Started"}
</p>
<div>
<button
type="button"
onClick={handleReactPress}
className="button is-grey"
>
React
</button>
<button
type="button"
onClick={handleGraphQLPress}
className="button is-dark"
>
GraphQL
</button>
<button
type="button"
onClick={handleAngularPress}
className="button is-grey"
>
Angular
</button>
</div>
</div>
);
};
const coursesReducer = (state, action) => {
switch (action.type) {
case "REACT":
return { react: true };
case "GRAPHQL":
return { graphQL: true };
case "ANGULAR":
return { angular: true };
default:
throw new Error();
}
};

Do we not need Redux anymore?

Conclusion

--

--

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
Adhithi Ravichandran

Software Consultant, Author, Speaker, React Native|React|GraphQL|Cypress Dev & Indian Classical Musician