Passing setState to child component using React hooks

Nicholas Porter picture Nicholas Porter · Jan 22, 2020 · Viewed 7.7k times · Source

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.

Answer

BRose picture BRose · Jan 22, 2020

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.