Table of contents
TogglePreface
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:
- What is useState?
- Creating an Evaluation UI Component
- Refactoring for this component
- Add the useState hook to this component
- Added setState as a new modifier for evaluation components.
- 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:
- 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
- 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 'react' import { FaStar } from 'react-icons/fa' export default function App() { return (
)
}
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.
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
{createArray(totalStars).map((n, i) =>
i} onSelect={() => setSelectedStars(i + 1)} /> )}
{selectedStars} of {totalStars} stars
}
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 'react' import { useState } from 'react'; import { FaStar } from 'react-icons/fa' const Star = ({ selected = true, onSelect = f => f }) => (
) const createArray = length => [...Array(length)]; export function StarRating({ totalStars = 5 }) { const [selectedStars, setSelectedStars] = useState(3) return
{createArray(totalStars).map((n, i) =>
i} onSelect={() => setSelectedStars(i + 1)} /> )}
{selectedStars} of {totalStars} stars
}
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 'react' import { FaStar } from 'react-icons/fa' const Star = ({ selected = true }) => (
) const createArray = length => [...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 (
{[...Array(totalStars)].map((n,i)=>{
{starSelected} of {totalStars} stars
)
}
}
Conclusion
This React article is more programmatic and shows the visual interface through a real-world example, as well as a separate comparison to earlier writing styles.Feel free to leave a comment if you have any suggestions or questions!
If you like this series of articles, please do not hesitate to click like and share it so that more people can see it!
Quote
React Vernacular Campaign 12-React Hook-useState 01
React Vernacular Campaign 13-React Hook-useState 02
React Vernacular Campaign Series
React Lifecycle - React Vernacular Campaign 10
React Props - React Vernacular Campaign 09
Building a React Project - React Vernacular Campaign 08
Babel & Webpack & NPM - React Whitepaper Campaign 07
React JSX - React Vernacular Campaign 06
How React Works - React Vernacular Campaign 05
JavaScript Advanced Functions - React Vernacular Campaign 04
JavaScript Async Await - React Vernacular Campaign 03