Home > Mobile >  will component reload when useState's initial value is updated in react?
will component reload when useState's initial value is updated in react?

Time:10-12

const [MIV, setMIV] = useState(MIValues);

MIValues <- this data is received from props, If this data updated in other component and passed to here will the MIV has the updated value ?

CodePudding user response:

useState is the initial state. It is like constructor in class.useState isn't used to update the state on re-render.

As React docs says:

Does useEffect run after every render? Yes! By default, it runs both after the first render and after every update. (We will later talk about how to customize this.) Instead of thinking in terms of “mounting” and “updating”, you might find it easier to think that effects happen “after render”. React guarantees the DOM has been updated by the time it runs the effects.

Component will be updated if you use useEffect:

const [MIV, setMIV] = useState(MIValues);

useEffect(() => {
    setUser(props.user);
}, [MIValues])

CodePudding user response:

You should use useEffect for it.

const [MIV, setMIV] = useState();
useEffect(() => {
    setMIV(MIValues);
}, [MIValues])

CodePudding user response:

Yes, component will reload automatically by react if the props(MiValues) is updated in parent component.And if you want to do something conditionally only when (MiValues) is updated, you can make use of useEffect hook.

CodePudding user response:

Yes, Example

Component Test1:

import React from 'react';
import { App } from './App.jsx'

    export function Test1() {
      return (
        <App MIVValues={22} />
      );
    }

Component Test2:

import React from 'react';
import { App } from './App.jsx'

export function Test2() {
  return (
    <App MIVValues={32} />
  );
}

App Component:

import React, {useState} from 'react';

export function App(props) {
  const [MIV, setMIV] = useState(props.MIVValues);

  return (
    <p style={{color: '#FFF'}}>{MIV} Test</p>
  );
}

Index.js

import React from 'react';
import ReactDOM from 'react-dom/client';

import { Test1 } from './test1.jsx';
import { Test2 } from './test2.jsx';

ReactDOM.createRoot( 
  document.querySelector('#root')
).render(<><Test1 /><Test2 /></>)

Output:

22 Test

32 Test
  • Related