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

Push state of reactive value to dependencies

I have an object: dynamicJSON that is changing. I would like to pass this object down to multiple dependencies: componentA, componentB. I also want the parts of the dependencies using the object to render when the object is changed.

I tried the useContext Hook, but received a dependency cycle error. What is the proper way to pass reactive values down to dependencies in react?

App.js

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

import { componetA } from "compA"
import { componetB } from "compB"

import { fetchLatestValue} from "api/fetchLatestValue"

import { useEffect } from "react"

export default function App() {
const dynamicJSON = ???;

  useEffect(() => {
    let timeoutId;
    async function getlatestValue() {
      try {
        const data = await fetchLatestValue();
        // update dynamicJSON here.
      } catch (error) {

      }
      timeoutId = setTimeout(getlatestValue, 1000 * 1);
    }

    getlatestValue();

    return () => {
      clearTimeout(timeoutId);
    };
  }, []);

  return (
    <componetA />
    <componetB />
  );
}

compA


export default function componentA() {
const dynamicJSON = ???;

return(
  <div>
    {dynamicJSON.value}
  </div>
)
};

>Solution :

Have you tried useEffect() with a dependency array? If anything in the dependency array is changed, the hook function will be triggered.

Reference: https://reactjs.org/docs/hooks-reference.html#conditionally-firing-an-effect


Sorry I mis-read your question, you should pass dynamicJSON into both components as a prop. Make dynamicJSON a state is also a good idea.

Rule of thumb: if a prop or state of a component is changed, then this component is rerendered.

import { ComponentA } from "compA";
import { ComponentB } from "compB";

import { useEffect, useState } from "react";

export default function App() {
  const [dynamicJSON, setDynamicJSON] = useState([{}]);
  //...omit

  return (
    <ComponentA dynamicJSON={dynamicJSON}/>
    <ComponentB dynamicJSON={dynamicJSON}/>
  );
}

CompA.js

export default function ComponentA(props) {
  const { dynamicJSON } = props;
  return(
    <div>
      {dynamicJSON.value}
    </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