one-hand-octopus
one-hand-octopus

Reputation: 2743

How to detect props changes in React?

I have 2 components: Radiobuttons and RadioOutput, where RadioOutput accepts a props from Radiobuttons. On click of the radio buttons, I can console log the props change as follows:

Radiobuttons.js

import React, { useState } from 'react';
import RadioOutput from './RadioOutput';

const Radiobuttons = () => {
    const [cause, setCause] = useState(null);
    const handleClick = (e) => {
        setCause(e.currentTarget.value)
    };
    return (
        <>
            <input type="radio" id="html" name="fav_language" value="HTML" onClick={handleClick}/>
            <label for="html">HTML</label><br />
            <input type="radio" id="css" name="fav_language" value="CSS" onClick={handleClick}/>
            <label for="css">CSS</label><br />
            <input type="radio" id="javascript" name="fav_language" value="JavaScript" onClick={handleClick}/>
            <label for="javascript">JavaScript</label>
            <RadioOutput cause={cause}/>
        </>
    )
};

export default Radiobuttons;

RadioOutput.js:

const RadioOutput = ({cause}) => {
    console.log(cause);
    return null;
};

export default RadioOutput;

My question is, is there a way I can detect the changes of cause inside RadioOutput? Maybe something like this:

const RadioOutput = ({cause}) => {
    // on change of cause, do something;
    return null;
};

Upvotes: 1

Views: 1337

Answers (1)

Gulam Hussain
Gulam Hussain

Reputation: 1763

RadioOutput will automatically re-render whenever causes value changes. But if you want to perform some side effects that depends only on cause value change, you can use useEffect hook.

useEffect will execute the function whenever cause value changes.

More about useEffect here https://reactjs.org/docs/hooks-effect.html

import React, {useEffect} from "react";

const RadioOutput = ({cause}) => {

    useEffect(()=>{
      console.log("runs whenever cause changes")
    },[cause])

    return null;
};

Upvotes: 7

Related Questions