Home > Software design >  Is parsing state from child component up in react a good practice
Is parsing state from child component up in react a good practice

Time:12-03

I am trying to change the state in the App components from a child components and I fell i would result to an issue later in my app

i tried passing the setFunction down to the child components then having it change the value in the app components

CodePudding user response:

You'll need to be careful while doing it, but yes, you can do it. Basically the issue you can encounter while doing this is: if the child AND the parent component try to update the state, thus leading to an infinite loop. (child updates the states which leads parent to re-render, and then updates the states, which leads the child to re-render etc...)

But if your parent component only "reads" from it, that's fine.

One another way to pass data to ANY component in your app would be to use React Contexts, but that's only if you need in many places. If that's just between one component and its child, the way you've done it is fine.

CodePudding user response:

In general, it is not a good idea to pass state from a child component to a parent component in React. Instead, it is better to manage the state in the parent component and pass the necessary data and functions to the child components as props. This helps to keep the child components reusable and makes the application easier to manage and maintain.

-------- another way -----------

It depends on the specific scenario and the design of the application. In general, it is better to avoid parsing state from a child component up to the parent in React, as it can lead to unnecessary complexity and can make the code more difficult to manage and maintain. Instead, it is often better to use a state management library like Redux or MobX to manage the global state of the application and allow components to access and update the state in a more organized and predictable way.

  • Related