React Hook useState – React Vernacular Campaign 11

React11-React-Hook-useState

Preface

The previous article explains more about React syntax, React Lifecycle - React Vernacular Campaign 10 We learned about the three phases of the React lifecycle, and we learned about the lifecycle of class objects and function objects. This post explains useState in Hooks with a real-world example:

  1. What is useState?
  2. Creating an Evaluation UI Component
  3. Refactoring for this component
  4. Add the useState hook to this component
  5. Added setState as a new modifier for evaluation components.
  6. Older versions of React state management writing

What is useState?

useState is a Hook in React that is used to add state to a function component via the useStateWe can define and manage the state data in the function element.

useState Returns an array with two values in it:

  1. Current state: When the component is first rendered, its value will be equal to the value we passed to the useState The initial value of the
  2. set function: This function is responsible for updating the value of the state and triggering a re-rendering of the component.
				
					const [state, setState] = useState(initialState)
				
			

Create a UI component for evaluation

We're going to use the React tutorials by Alex Banks & Eve Porcello for this one, but some of the code has been modified a bit.

Since this post is about creating a UI page, we need to use the react-icons package, which has a library of hundreds of SVGs built in. We can download the react-icons package by typing the following command in the terminal.

				
					npm i react-icons
				
			

Through Building a React Project - React Vernacular Campaign 08 This is a step-by-step guide to quickly building a react project.

				
					npx create-react-app my-app cd my-app npm start
				
			

This will start a react project locally, then modify App.js as below to get the following UI components.

				
					import React from &#039;react&#039; import { FaStar } from &#039;react-icons/fa&#039; export default function App() { return (<div>
        <fastar color='red'></fastar>
        <fastar color='red'></fastar>
        <fastar color='red'></fastar>
        <fastar color='red'></fastar>
        <fastar color='red'></fastar>
    </div>)
}

				
			
react-hook-usestate-01

Refactoring for this component

Refactor means to rewrite the code without changing the result of the program, so that the overall quality of the code can be improved.

Next, we need to reorganize the code according to the original code, so that the overall code becomes more concise. Here we can divide it into three parts:

First Steps in Reorganization

You can first split FaStar into separate components and give parameters to this component, the parameter given here is the selected quotient, the default value is true.

				
					const Star = ({ selected = true }) => ( <FaStar color={selected ? 'red' : 'gray'}></FaStar> )
				
			

Step 2 of the reorganization

Creates a function that, given a length, can be quickly assembled into an array.

				
					const createArray = length => [...Array(length)];
				
			

Step 3 of the reorganization

Finally, in the UI you're using, you're using an ES6 array map, which returns the corresponding index and components in the map function.

				
					export default function App({ totalStar = 5 }) { return createArray(totalStar).map((n, i) => <Star key={i} />) }
				
			

When the reorganization is completed, the original program execution result is unchanged, and the final five stars will still be sent back.

				
					import React from 'react' import { useState } from 'react'; import { FaStar } from 'react-icons/fa' const Star = ({ selected = true }) => ( <FaStar color={selected ? 'red' : 'gray'}></FaStar> ) const createArray = length => [...Array(length)]; export default function App({ totalStar = 5 }) { const [selectedStars] = useState(3) return createArray (totalStar).map((n, i) => <Star key={i} selected={selectedStars > i} />) }
				
			

Add the useState hook to this component

The refactored code does not yet have any associated data or state. Here we can use some hooks to manage the state of the function.

useState( ) is the first function we will learn when we learn hooks. We can give the state of a component by using the following syntax.

				
					const [variable,setVariable] = useState("");
				
			

In the following code example, we add a new state called selctedStars to the App function and set the value of selctedStars to 3. Then we can render against this variable in this component.

				
					import React from 'react' import { useState } from 'react'; import { FaStar } from 'react-icons/fa' const Star = ({ selected = true }) => ( <FaStar color={selected ? 'red' : 'gray'}></FaStar> ) const createArray = length => [...Array(length)]; export default function App({ totalStar = 5 }) { const [selectedStars] = useState(3) return createArray (totalStar).map((n, i) => <Star key={i} selected={selectedStars > i} />) }
				
			

Because selctedStars is set to 3, and also set the discriminant in FaStar element. If selected is true, it will be red, otherwise it will be black, and you will end up with the following component.

react-hook-usestate-02

setState New Modify function

useState( ) can not only give the default value, but also can modify its value, which can be done by using setState.

In StarRating, you can add a new setSelectedStars that can be used in the component. This also adds a new function to Star called onSelect and passes in the setSelectedStars.

				
					export function StarRating({ totalStars = 5 }) { const [selectedStars, setSelectedStars] = useState(3) return <div>
       {createArray(totalStars).map((n, i) =&gt; 
		<star 
    		key="{i}" 
    		selected="{selectedStars" > i} onSelect={() =&gt; setSelectedStars(i + 1)} /&gt; )}
        <p>
            {selectedStars} of {totalStars} stars
        </p>
    </div>
}
				
			

Here, we pass in a function called setSelectedStars into the onClick function, so that all the stars will trigger setSelectedStars( ) when they are clicked.

				
					const Star = ({ selected = true, onSelect = f => f }) => ( <FaStar color={selected ? 'red' : 'gray'} onCLick={onSelect}></FaStar> )
				
			

The full code for useState is also attached:

				
					import React from &#039;react&#039; import { useState } from &#039;react&#039;; import { FaStar } from &#039;react-icons/fa&#039; const Star = ({ selected = true, onSelect = f =&gt; f }) =&gt; (
    <fastar color="{selected" ? 'red' : 'gray'} onclick="{onSelect}"></fastar>
) const createArray = length =&gt; [...Array(length)]; export function StarRating({ totalStars = 5 }) { const [selectedStars, setSelectedStars] = useState(3) return <div>
        {createArray(totalStars).map((n, i) =&gt; 
		<star 
    		key="{i}" 
    		selected="{selectedStars" > i} onSelect={() =&gt; setSelectedStars(i + 1)} /&gt; )}
        <p>
            {selectedStars} of {totalStars} stars
        </p>
    </div>
}

				
			

Older versions of React state management writing

The old version refers to the earlier way of writing classes, since hooks could only be used for functions. This one shows the state management of classes, but it's a bit more difficult to understand because classes have some object-oriented concepts.

Compared to useState for presetting and updating the data state, the class component uses a constructor, which can give starSelected a default value of 0, and also binds to the function change declared in the class, and then renders the component with the render( ) function.

				
					import React, { Component } from &#039;react&#039; import { FaStar } from &#039;react-icons/fa&#039; const Star = ({ selected = true }) =&gt; (
    <fastar color="{selected" ? 'red' : 'gray'}></fastar>
) const createArray = length =&gt; [...Array(length)]; export default class StarRating extends Component { constructor(props) { super(props); this.state = { starSelected: 0 }; this.change = this. change.bind(this); } change(starSelected){ this.setState({starSelected}); } render(){ const {totalStars} = this.props; const {starSelected} = this.state; return (
            <div>
                {[...Array(totalStars)].map((n,i)=&gt;{
                    <Star 
                        key={i} 
                        selected={i &lt; starSelected} onClick={()=&gt;this.change(i+1)} /&gt; })}
                <p>
                    {starSelected} of {totalStars} stars
                </p>
            </div>
        )
    }
}
				
			

Leave a Comment

Your email address will not be published. Required fields are marked *

en_USEnglish