Home > OS >  Should child component have states? - React
Should child component have states? - React

Time:06-03

Suppose, we have the parent component App, and it has a child component Search.

For this example:

The Search component displays the text typed in its input field, via setState, i.e:

const Search = () => {
  const [searchTerm, setSearchTerm] = React.useState("");
  const handleChange = (event) => {
    setSearchTerm(event.target.value);
  };
  return (
    <div>
      <label htmlFor="search">Search: </label>
      <input id="search" type="text" onChange={handleChange} />
      <p>
        Searching for <strong>{searchTerm}</strong>.
      </p>
    </div>
  );
};

Method 1: let the child component Search have its own state.
Should the Search component have its own state, i.e use UseState()? Or is this a bad practice?


Method 2: let the parent component App manage the child's state.
Should the value from the Search component be passed up to the parent component App and then let the App component manage the state via setState(), then pass the updated value back down to the search component?

Which method is a better practice?

CodePudding user response:

If you need value of search anywhere else in your project then it's better to manage states centrally(if project is small) or use useContext hook. Else if value will only be needed by Search component then it's better that state is managed in component itself.

CodePudding user response:

First of all, what do you need for your project? In fact, you are acting on this question. if parent component will use state in app.js, you should pass state to parent component. but iif not needed, you should setState in child component.

CodePudding user response:

As a rule of thumb, the state should be as far down the hierarchy as possible. The main reason to lift the state further up is if you need to access the state from multiple components.

Then you can lift it to the parent, and pass it to multiple children. If the state need to be accessed in many places, you can use a context or some other state managing library.

CodePudding user response:

A good way to find an answer to this question is to think contextually.

The search a self contained component with no impact outside of its own context

Then you should keep the state closer to where it will be manipulated : inside the component.

Is it part of a whole and is a system that reaches the parent or even components outside of tree ?

In this case you should rely on the Context API or use a state management library like Redux that will avoid performance pitfall in some complex cases. Having your state managed by the Root component makes it available to your whole App and prevents you from doing painful prop drilling.

  • Related