I am new to React Hooks. I have been learning this language with a number of questions in stackoverflow. Even though I have explored the other questions here for 3 days to figure out my following issue, I have not found a proper way.
The following link is my simplified code:
import React, { useState } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
function App() {
const [render, setRender] = useState(true);
const [show, setShow] = useState(true);
return (
<div className="App">
<button onClick={() => setRender(!render)}>Render</button>
{show ? (
<div>
<h1>Hello CodeSandbox</h1>
<button onClick={() => setShow(!show)}>Hide</button>
</div>
) : /// setShow(true) <- How can I update it?
null}
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
From my example, what I want to try is, when Hide button is clicked, Hello CodeSandbox disappears because it is null after show becomes false. However, the issue is when I click Render button, it should display Hello CodeSandbox again but it doesn't. I believe the reason is because show state still remains false. Thus, I want to update show state to true once Render button is clicked so that Hello CodeSandbox appears.
Is it possible if I can update state before using null? Or is there any better way?