Middle
What is state in React and why is it needed?
sobes.tech AI
Answer from AI
State in React is an object that stores the component's data affecting its rendering and behavior. It is needed so that components can respond to data changes and update the UI dynamically.
For example, if you have a button that changes text when clicked, the state stores the current text, and when the state updates, React re-renders the component:
import React, { useState } from 'react';
function Example() {
const [text, setText] = useState('Click me');
return (
<button onClick={() => setText('Thank you!')}>{text}</button>
);
}
Thus, state allows creating interactive and dynamic interfaces.