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

Time:08-17

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

CodePudding user response:

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.

CodePudding user response:

React components work with state and props. Whenever the state or props of a component change, React re-evaluates that component and its children, and if it determines that there are any changes to be made to the DOM, it makes them.

If you create a regular variable using let or const, and its value is updated, React will not update the DOM and hence neither that component nor its children will re-render.

  • Related