I have a SettingsDialog
component that has the initial settings passed in as props. I'm then using useState
to set the current form values initially to the passed in settings:
export default function SettingsDialog({ settings }) {
const [values, setValues] = useState(settings);
}
However, this doesn't seem to be working. The values
state object is always an empty object. If I add two console.log
statements:
export default function SettingsDialog({ settings }) {
const [values, setValues] = useState(settings);
console.log('settings:', settings);
console.log('values:', values);
}
the first logs out the settings object being passed in, but the second logs out an empty object.
Am I not understanding how the useState
hook is supposed to work, or am I just doing something wrong?
To set a conditional initial value for useState in React:Pass a function to the useState hook. Use a condition to determine the correct initial value for the state variable. The function will only be invoked on the initial render.
The answer: They're just queues setState , and React. useState create queues for React core to update the state object of a React component. So the process to update React state is asynchronous for performance reasons. That's why changes don't feel immediate.
The key difference is that the initial value of the state defined by useState can be anything you want it to be. It no longer has to be an object. A string, a number, an object, undefined , null - anything goes!
When you manage state using the useState hook, all you have to do is call your setState function passing it the initial state. Copied! const resetState = () => { setEmployee(initialState); }; With the useReducer hook, you have to add an action handler for the RESET state that returns the initial state.
The reason why you get the empty values (but the settings has value) is because, when you render the page the Dialog got initialized, but at this time, the value of both settings and values are null; then when you open the Dialog, the settings value has been initialized. But the values hasn't get updated;
if you wanna the values keep updating with settings, add:
useEffect(() => {
setValues(settings);
}, [settings]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With