I'm curious if passing setState
as a prop to a child (dumb component) is violating any "best practices" or will affect optimization.
Here is an example where I have the parent container passing state
and setState
to two child components, where the child components will call the setState
function.
I do not explicitly call setState
in the children, they reference a service to handle the correct setting of state properties.
export default function Dashboard() {
const [state, setState] = useState({
events: {},
filters: [],
allEvents: [],
historical: false,
});
return (
<Grid>
<Row>
<Col>
<EventsFilter
state={state}
setState={setState}
/>
<EventsTable
state={state}
setState={setState}
/>
</Col>
</Row>
</Grid>
)
}
Example of dashboard setState service
function actions(setState) {
const set = setState;
return function () {
return ({
setEvents: (events) => set((prev) => ({
...prev,
events,
})),
setAllEvents: (allEvents) => set((prev) => ({
...prev,
allEvents,
})),
setFilters: (name, value) => set((prev) =>
({
...prev,
filters
})
),
})
}
}
So far I haven't noticed any state issues.
First, you'll need to create two components, one parent and one child. Next, you'll import the child component in the parent component and return it. Then you'll create a function and a button to trigger that function. Also, you'll create a state using the useState Hook to manage the data.
First, click on App and observe its state under the Hooks section on the right pane. Second, click on a given player component and examine its props. Finally, click on any of the items in the page and see how the state and props of the parent and child components are updated, respectively.
We can set Parent State from Children Component in ReactJs using the following approach. We will actually set the state of a parent in the parent component itself, but the children will be responsible for setting. We will create a function in parent to set the state with the given input.
It is ok to call a function from the child to set the state of the parent, however there is a couple things to keep in mind when doing this
1) I hope you aren't actually calling the function as "setState" as generally you don't want to this, from a purely syntactical standpoint
2) Realize that you are affecting the state of the parent and not the child when calling the function from within the child. This could lead to some funky results if you lose track of what data you are intending to manipulate and from where.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With