One of the most important parts of any application is managing state. State along with props is the data that we display on the view screen, We use state to display the data which can or will be changed in the app.
React.useState()
is the hook provided by react to manage state in functional component. It return an array with value and method to set the value
const [value, setterMethod] = React.useState(initialValue);
React useState syntax
const [theme, setTheme] = React.useState('darkMode');
React useState() example
👍 Good Practice :
Multiple useState hooks
Although you can use useState to capture all the state of your component. It is not a good practice.
❌ const [state, setState] = React.useState({ theme: 'dark', primary: 'Red' })
Breaking into individual state make it more readable and easily maintainable.
✅ const [mode, setMode] = React.useState('dark');
✅ const [primayColor, setPrimaryColor] = React.useState('Red');
To perform long operation for InitialValue use the function approach
Since inital state computation happens on every render use the functional argument as it runs only once.
const [mode, setMode] = React.useState(() => {
/* some long operation */
});
👎 Traps:
Setter Methods overrides values and do not merge object or array
const [state, setState] = React.useState({ theme: 'dark', primary: 'Red' });
If we set state like
❌ setState({theme: 'light'})
it will replace the state with only this value and delete all the other values
state={theme: 'light'}
. Instead we should copy the object and then replace your new value like
✅ setState(prevState => {...prevState, theme: 'light'})
This method will create a new object with all the previous state and update the theme to light. New value will retain the old value
state={{ theme: 'light', primary: 'Red' }