Here's the UI
Where I click the first button, then click the second button, it shows value 1, but I expect it to show value 2, since I set the value to 2. What's the problem and how should I address that?
Here's the code:
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import React, {
useState,
useEffect,
useMemo,
useRef,
useCallback
} from "react";
const App = () => {
const [channel, setChannel] = useState(null);
const handleClick = useCallback(() => {
console.log(channel);
}, [channel]);
const parentClick = () => {
console.log("parent is call");
setChannel(2);
};
useEffect(() => {
setChannel(1);
});
return (
<div className="App">
<button onClick={parentClick}>Click to SetChannel 2</button>
<button onClick={handleClick}>Click to ShowChannel 2</button>
</div>
);
};
const rootElement = document.getElementById("root");
const root = createRoot(rootElement);
root.render(<App />);
Here's the codesandbox
Add a dependency to the useEffect hook, if you don't add any dependency it will just re-run on every state change.
Change this:
useEffect(() => {
setChannel(1);
});
To this:
useEffect(() => {
setChannel(1);
}, []);
useEffect(() => {
setChannel(1);
});
Runs on every render, so it's always reverting back to 1
Your problem is that you are setting channel value to 1 every render. You have 2 options.
this.setState({channel: 1}) in the componentDidMount method.class App extends React.Component {
constructor(props) {
super(props);
this.state = {channel: 1};
}
handleClick=(evt)=> {
console.log(this.state.channel);
}
parentClick=(evt)=> {
this.setState({channel: 2});
}
render() {
return (
<div className="App">
<button onClick={this.parentClick}>Click to SetChannel 2</button>
<br /><br />
<button onClick={this.handleClick}>Click to ShowChannel 2</button>
</div>
);
}
}
PS: It's not clear what you're trying to do & your sandbox is quite different from the code you have posted here.