Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

useState not setting initial state?

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?

like image 477
Joe Attardi Avatar asked Sep 08 '19 19:09

Joe Attardi


People also ask

How do I set initial value in useState?

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.

Why useState is not updating immediately?

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.

What is the initial value of useState?

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!

How do you reset state of useState?

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.


1 Answers

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]);
like image 119
KATHERINE Avatar answered Nov 15 '22 03:11

KATHERINE