Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

if a useState holds an object, does setting it to an identical object trigger downstream dependencies?

const [stuff, set_stuff] = useState{a: 1}


...

set_stuff({a: 1})

when set_stuff({a: 1}) is run, will it trigger downstream dependencies that listen to stuff?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

If they listen to stuff, yes.

If they listen to a property of stuff that’s equal to the previous value at that property (like a and 1), no. Example:

const App = () => {
  const [stuff, setStuff] = React.useState({a: 1});
  React.useEffect(() => {
    console.log('Will trigger later because stuff changed');
  }, [stuff]);
  React.useEffect(() => {
    console.log('Will not trigger later because stuff.a did not change');
  }, [stuff.a]);
  
  React.useEffect(() => {
    setTimeout(() => {
      setStuff({ a: 1 });
    }, 1000);
  }, []);
  return 'foo';
};

ReactDOM.render(<App />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading