Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 2897

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 61k
Author
Asked: November 26, 20242024-11-26T09:41:08+00:00 2024-11-26T09:41:08+00:00

React hooks: An advanced look at converting useState to useReducer

  • 61k

In my previous blog, I gave a basic demonstration on how to manage state with useReducer instead of useState. In this blog, I'll dive into a more complex example.

When managing state for a form, things can get complex quickly. Take this form, for example:

basic form

To manage the form's state locally with useState, it would look something like this:

  const [name, setName] = useState('') const [title, setTitle] = useState('') const [favoriteNumber, setFavoriteNumber] = useState('') const [favoriteColor, setFavoriteColor] = useState('')   
Enter fullscreen mode Exit fullscreen mode

This might seem manageable enough for now – but if the form needs to grow, one useState per input will turn your code into spaghetti before you know it! Let's take a look at how we can make state management more scaleable with useReducer using the same steps shown in my previous blog:

  1. Define an initial state and an action type.
  2. Replace the useState hook with the useReducer hook.
  3. Create a reducer function that takes a state and an action and returns a new state.
  4. Update the component to use the new state and dispatch functions returned by the useReducer hook, which should have the reducer and initial state passed in.

Following the steps above, we can convert our useState state to useReducer state.

1. Define an initial state and an action type:
  const initialState = {   name: 'Default name',   title: 'Default title',   favorite_number: '3',   favorite_primary_color: 'red', };  const INPUT_CHANGE = 'inputChange';   
Enter fullscreen mode Exit fullscreen mode

2. Replace the useState hook with the useReducer hook:
  import { useReducer } from 'react';  const FormComponent = () => {   const [formData, setFormData] = useReducer(formReducer, initialState);    // ... }   
Enter fullscreen mode Exit fullscreen mode

3. Create a reducer function that takes a state and an action and returns a new state:
  const formReducer = (state, action) => {   const stateCopy = { ...(state || {}) };    switch(action.type) {     case INPUT_CHANGE:       return {         ...stateCopy,         [action.payload.name]: action.payload.value       }      default:       return null;   } }   
Enter fullscreen mode Exit fullscreen mode

4. Update the component to use the new state and dispatch functions returned by the useReducer hook, which should have the reducer and initial state passed in:
  const FormComponent = () => {   const [formData, setFormData] = useReducer(formReducer, initialState);    const internalOnchange = (type, payload) => {     setFormData({ type, payload })   };    // ...    return (     <form>       <input         type="text"         id="name"         name="name"         onChange={event => {           internalOnchange(INPUT_CHANGE, {             name: event.target.name,             value: event.target.value,           });         }}       />      {/* ... */}      </form>   ); }   
Enter fullscreen mode Exit fullscreen mode

Step 4 is a little more complex in this example. In order to pass the type and payload to the reducer cleanly, I've implemented an internalOnchange helper function. Now the internalOnchange can be passed into any input on the form, as shown on the name input above.

As long as the name attribute of the input matches the data you want to change, that value in state will be changed. Now the form can have unlimited inputs with no need to change the state management functionality!

…unless the form gets even more complex?? Not a problem, you can add another action to your formReducer to manage any specialized inputs. To see this form as a completed project, check it out here on Github.

I've created the example form explained above – it changes state independently by action, but I've also included an option to change the data as a whole by manipulating the entire JSON directly. This is done by passing the entire changed JSON as the payload here and using an updateData action, created here. This project will look a little different than the blog example since it's done in TypeScript, I wanted to keep things simple in this blog so I explained it in JavaScript.

I hope this blog clearly explained using useReducer to handle state instead of useState. If you have any questions or comments, I'd love to hear what you've got!

programmingreacttutorialwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    ES6 - A beginners guide - Template Literals

    • 0 Answers
  • Author

    Understanding Higher Order Functions in JavaScript.

    • 0 Answers
  • Author

    Build a custom video chat app with Daily and Vue.js

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.