A React design pattern that allows a parent component to control the state of a child component. It involves passing a callback function from the parent component to the child component, which the child component will then call when it needs to update its state.
When should you use it?
You should use the Control Props pattern in React when you need to allow a parent component to control the state of a child component.
This pattern is especially useful in cases where a child component needs to be reusable and flexible, but the parent component still needs to have control over certain aspects of the child component's behaviour. For example, in a form component, the parent component may need to handle the submission of the form data, while the child component manages the form inputs.
Using the Control Props pattern allows the parent component to define the behaviour of the child component by passing down the necessary state and callback functions as props. This separation of concerns makes it easier to maintain and update the components since changes to one component will not affect the other.
Considerations:
In general, you should consider using the Control Props pattern when:
(1) You have a complex component that needs to be divided into smaller, more manageable components.
(2) You need to separate concerns between parent and child components.
(3) You want to create a reusable component that can be used in multiple parts of your application.
(4) You need to maintain tight control over the state of a component, while still allowing it to be flexible and customizable.
Example Code:
Here's an example code for implementing the Control Props pattern in React:
Parent Component:
Child Component 1:
Child Component 2:
In the above example, the Parent Component maintains the state of the checkbox using the useState hook and passes down the isChecked prop to Child Component 1 and Child Component 2. The Child Components then use this prop to modify their behaviour when the button is clicked. So the state in the parent component is passed as a prop and based on the prop received we can control the behaviour of the child components according to our convenience.
By using the Control Props pattern, the Parent Component can control the behaviour of the Child Components without tightly coupling the two components together. This makes the code more modular and easier to maintain.
I hope the above article helped you to get a basic understanding of the Control props pattern in react. For more such articles you can show your love by following me here on hashnode and liking this article ๐ .