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

Why local variables cannot be passed to child components in react?

I am a beginner in react and had the following basic doubt. I get response from an API in a functional component and I am passing this response to a child component so that the child component can use this data for rendering its content. This parameter passed to child component is appearing as empty in child component’s console logs even though it is appearing as expected in the parent component’s console logs (stored as local variable not state). Could someone please help to understand why state variables are required and just local variables are not sufficient here?

Thanks

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

>Solution :

If you want to pass anything to the child component it should be one of the observables. Meaning that when the variable changes the react component should know when to rerender the whole component based on your change.
My initial guess for why that is occuring is

  • Your variable is not observable (i.e you need to use useState to make it observable)

eg.
While the following code will rerender

  const [todo, setTodo] = useState([])

  useEffect(async () => {
        const api = await fetch(.....).then(res => res.json())
        setTodo(api) // assuming api will return you array of todo
  }, [])

The below will not rerender

  let todo = []

  useEffect(async () => {
        const api = await fetch(.....).then(res => res.json())
        todo = api // assuming api will return you array of todo
  }, [])

Since the todo on these are not observable.

However props are observable by default i.e the below component will rerender based on someObservable if it changes.

<SomeComponents canChange={someObservable.includes('a')} />

But on your above instance. Since the todo is static and not observable react will not run the render function. Hence your component will not rerender.

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