NextJs / Basics / Variable with state
State : Variables with state
-
Notes
State Variables
state variables trigger a re-render of the component whenever their value changes.
1. Normal variable does not update the DOM whenever the value of that variable is changed in the component after UI rendering
2. But state variable automatically update the DOM whenever the value is changed in the the component after UI rendering
const [ , ] = useState( ); eg: const [amount, setAmount] = useState(100); The first value, variableName, is our current state. It is used to read the data
The second value, setvariableName, is the function that is used to update the state. Note that the keyword 'set' is prepended to the variable to create state function
variableName is used to set the initial value
useState is used to declare the state variable
2. Read State
3. Update State{variableName} eg: {amount} setvariableName( ); eg: setAmount(200); Usage of state variable
State variables are normally used when fetching API data
Normal variable with UI
'use client' import React from 'react'; export default function Home() { var likeS=1; const handleClick = () => { likeS=likeS+1; console.log(likeS); }; return ( Hello React.
Start editing to see some magic happen!
Like button is clicked after the rendering of the UI. So the value changed in the variable 'likeS' will not update the DOM State variable with UI
Import useState'use client' import React from 'react'; import { useState } from "react"; export default function Home() { var likeS=1; const [likeD, setLikeD] = useState(1); const handleClick = () => { likeS=likeS+1; console.log(likeS); }; const handleClickState = () => { setLikeD(likeD + 1); }; return ( Hello React.
Start editing to see some magic happen!
1. At the top of the component, import the useState Hook.
Initialize useStateimport { useState } from "react";
Read Stateconst [likeD, setLikeD] = useState(1);
Update State{likeD} setLikeD(likeD + 1); -
Multiple state variables
const [brand, setBrand] = useState("Ford"); const [model, setModel] = useState("Mustang"); const [year, setYear] = useState("1964"); const [color, setColor] = useState("red");