I currently have started learning React.js and I wonder how React listens for state changes?
I mean I know there is not any event listeners in Javascript for tracking variable change and I'm pretty sure that we can not listen for changing a variable (without using an interval to check the change) in Javascript natively...
But in React if you change a property of a state it will finds out the change instantly?!
How it's implemented in React?
I currently have started learning React.js and I wonder how React listens for state changes?
I mean I know there is not any event listeners in Javascript for tracking variable change and I'm pretty sure that we can not listen for changing a variable (without using an interval to check the change) in Javascript natively...
But in React if you change a property of a state it will finds out the change instantly?!
How it's implemented in React?
Share Improve this question asked Dec 24, 2020 at 21:39 user13849624user13849624 3- Have a read of something like w3schools./react/react_state.asp and let us know if you're still puzzled.. (And also if you're using redux, let us know) – Caius Jard Commented Dec 24, 2020 at 21:44
-
'>- no event listeners.. for tracking variables' - not entirely true, there's such thing as
Proxy
– Yevhen Horbunkov Commented Dec 24, 2020 at 21:51 -
1
Such function like
setState
only update the state and call the ponent again with new state value. Dan Abramov has a good explanation for this – kunquan Commented Dec 24, 2020 at 21:54
1 Answer
Reset to default 5React does not passively listen for state changes at all. The only way it knows the state changed is because you explicitly tell react to change the state. In class ponents, that's done with this.setState
:
class Example extends React.Component {
state = {
name: 'valentina';
}
ponentDidMount() {
setTimeout(() => {
this.setState({ name: 'jebediah' });
}, 1000);
}
// ...
}
In a function ponent, that's with the state-setter function returned by useState
:
const Example = (props) => {
const [name, setName] = useState('valentina');
useEffect(() => {
setTimeout(() => {
setName('jebediah');
}, 1000);
}, []);
// ...
}