How to detect props changes in React?

thi*_*edu 0 javascript reactjs

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;
Run Code Online (Sandbox Code Playgroud)

RadioOutput.js:

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

export default RadioOutput;
Run Code Online (Sandbox Code Playgroud)

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;
};
Run Code Online (Sandbox Code Playgroud)

Gul*_*ain 6

RadioOutput每当causes值更改时将自动重新渲染。但是如果你想执行一些仅依赖于cause值变化的副作用,你可以使用useEffect钩子。

useEffect每当cause值更改时将执行该函数。

更多关于useEffect这里 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;
};
Run Code Online (Sandbox Code Playgroud)