2

I moved from CRA to Next.js and I'm struggling with a concept (that could be related to React as well in fact):

How do you pass props (like data/setter from useState) to child components from a page?

Here's a limited example to illustrate my question:

export default function MyProductPage({ props }) {
    const [data, setData] = React.useState(props.data)

    return (
        <Fragment>
            <h1>Products :</h1>
            <Products data={data} setData={setData} />
        </Fragment>
    )
}

function Products({ data, setData }) {
    return (
        <Grid>
            ...
            {data.map(product => <Product id={product.id} product={product} setData={setData} />)
            ...
        </Grid>
    )
}

function Product({ id, product, setData }) {
    function updateProduct() {
        // update a product info by updating the state in the parent
        setData(...)
    }

    return (
        // render product card to show info
    )
}

export function getServerSideProps() {
    const data = fetch(...)

    return { props: { data } }
})

I know this works, but if you have n children between MyProductPage and the component Product, you would have to pass the data={data} setData={setData} to all the intermediary children in order to allow Product to update itself and reflect that change "state-wise", which seems wrong.

In the past, I was using Redux to perform the data fetching and hold the data in the global store. That would make the data available to all the components. But it feels wrong to hold remote data now that I can leverage SSR from Next.js.

I could create a specific context using useContext for the page so it would be cleaner. Is that it?

I would like to make the correct design choice. I'm pretty sure there are some best practices or guidelines on that matter, but I was not able to find it, or formulate what I'm looking for.

Binajmen
  • 486
  • 2
  • 6
  • 18

0 Answers0