A state in React holds information that impacts the DOM render and is managed within a component.
Whenever a state is changed the component re-renders thus manipulating the DOM.
You can set a default value for the state and you can also set multiple values e.g an object, in this example the default value for customText state is Watermelon.
const [customText, setCustomText] = useState('Watermelon');The easiest method to change or update the state is to use setState()
setCustomText('Apple');This would now change the customText state to Apple and update the DOM content to reflect this.
React state example
This Codepen example has a React state with an input that is used to set the state when its value changes.
Explanation:
Whenever the input value is changed it will call on the function handleInputChange and the value is set as the customText state.
<input type="text" value={customText} onChange={handleInputChange} className="..."/>Here the handleInputChange function sets the customText state to the inputs value via the event target method.
let handleInputChange = (event) => {
setCustomText(event.target.value);
}Now just to better showcase the state is this output, If the input is empty “The text is empty will” be shown else it will output the state
{
customText !== "" ? (
<p>
The text is: <span className={"text-bold text-blue-400"}{customText</span>
</p>
) : (
<p>The text is empty</p>
);
}