DEV Community

Aissa BOUGUERN
Aissa BOUGUERN

Posted on

Re-render React.js Child Component By Passing Object Prop

I'm working on a Quiz app,

I have a list of questions, every question must be answered in 30 seconds. And when the user click NEXT button, I want to restart the countdown.

The countdown (child component), as you can see, accepts two properties: time and onComplete.

<Countdown time={30} onComplete={onComplete} />

I want to restart the countdown by resetting time value to 30. The problem is that the <Countdown /> will not detect that change because of React.js props equality check.

So, to surpass this situation, I now passe time prop as an object.

Here is an example:

<Countdown time={{time: 30}} onComplete={onComplete} />

Now, every time I call setTime({time: 30}) in the parent component, the countdown component detects that change and it restarts successfully.

const Quiz = () => {

    const [time, setTime] = React.useState({time: 30});

    function goToNext(){
        setTime({ time: 30 });
        ...
    }

    return (

        <Countdown time={{time: 30}} onComplete={onComplete} />

        <Question current={1} />

    )

});

I understand why React.js does not detect equality here, and I came up with this solution after reading this medium article.

The only thing I want to know is:

Is this a good solution for this case ? Or I can do better ?

Waiting for your responses...

Thank you,

Top comments (2)

Collapse
 
georgecoldham profile image
George • Edited

You are using useState in an unusual way...

I would rewrite this as:

import React, { useState } from 'react';

const Quiz = () => {

    const [time, setTime] = useState(30);

    function goToNext(){
      setTime(30);
      ...
    }

    return (
      <>
        <Countdown time={time} onComplete={onComplete} />
        <Question current={1} />
      </>
    )

});

The article you linked to is for an older way of using React, the move to hooks (which you are using) addresses many of the concerns in it.

Without having more of the code its hard to help more. Feel free to send me a message if you want more help etc.

Collapse
 
aissabouguern profile image
Aissa BOUGUERN

Thank you George!

I sent you a message in the chat.