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?
Edit:
I don't know why this question is flagged as opinion based. I understand there will some disagreement, but that is bound to happen when a question revolves around using the correct design pattern. If you disagree, then why not flag all the stack overflow questions that revolves around which design pattern to use, or the "correct SQL database/table to use" as opinion based as well.
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.
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.
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.