Home > Mobile >  Push state of reactive value to dependencies
Push state of reactive value to dependencies

Time:02-20

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

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>
)
};

CodePudding user response:

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>
  )
};
  • Related