How to Manage State in React Components
Q. What is state in React components?
Ans:- Components need to remember kind of component-specific memory, is called state.
Q. Why we need state in React components?
Ans:- If we use local variables in component it doesn't work due to below reasons,
Local variables doesn't persist between renders that means whenever component re-renders it renders from scratch and creates those local variables without considering it's previous values.
Changes to local variables won't trigger renders.
Whenever we need to store component data we expect 1. data to be retain during renders and 2. should trigger re-render with new data.
To retain component specific data we use useState
hook from react library. It returns us two things
1. state
2. updater method to update state.
We can declare multiple states with different context. We can pass default value to useState(<defaultValue>)
so that it can remember this when state is not set/updated.
import { useState } from 'react';
const App = () => {
const [state, setState] = useState();
return (
<>
{state}
<input value={state} onClick={(e) => setState(e.target.value)}/>
</>
)
}