React has many great features to it that help create javascript. One way to impact the DOM is through state. React makes what is required in regular Javascript to update DOM much easier with fewer steps and simpler syntax. The unique feature to state is that every time it is updated the page re-renders.
State is data that is dynamic in a component. It can be updated over time as the application is updated and changed by the user. All these updates will be reflected in the webpage as they are changed.
When it is required to update an item that needs to be shown on the page instead of updating a variable you are to update state as you can have the issue of the variable updating but the page would not re-render and the updated variable would not be displayed.
The way to use state in react is a multi step process. First you need to use the react hook: import { useState } from "react"
This lets you use react's backend information and all that is required to update state.
Then you need to create a state variable. An example of this is:
const [count, setCount] = useState(0)
Above you are setting the state array for the variable count and setting the initial value of count to 0 as that is what is put in the parentheses of useState.
You then can create a function to update state and every time this occurs the count variable will be updated and the page will be re-rendered to show the updated count. See the full example of this below. The starred area is the last piece of the puzzle as discussed above.
import { useState } from "react"
function Counter() {
const [count, setCount] = useState(0);
**function increment() {
setCount(count + 1);
}
return {count};
}**
Top comments (0)