With hooks, you no longer need a callback from the setState
function. Now, you can set state with the useState
hook, and listen for its value to update with the useEffect
hook. The optional second parameter of the useEffect
hook takes an array of values to listen to for changes. In the example below, we are just monitoring one value for changes:
const Example = () => {
const [value, setValue] = useState(null);
useEffect(() => {
// do something when value changes
}, [value]);
return (
<button onClick={() => setValue('Clicked!')}>
Click Me!
</button>
);
};
Read more about the useEffect
hook here.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…