React useState as a toggle triggers Re-render and re-initializes false on re-render

33 Views Asked by At

I have a simple question. I am using a React toggle function based on useState toggle the rendering of a component. It works, but on the Re-render of the parent component where the toggle function is defined it re-initializes that state as false and therefore hides the RegisterForm component once again. What am I missing here?

import RegisterForm from "./forms/Registerform";
import LoginForm from "./forms/LoginForm";
import { useState } from "react";
import useToggle from "./helpers/useToggle";
const LoginOrRegister = () => {
    const [toggle, setToggle] = useToggle(false)

    return(
    
        <>
        <div className="login">
        <p>Login to your user account</p>
        <LoginForm/>
        </div>
        <div className="register">
            <a href="" onClick={setToggle}>Not yet signed up? Register here</a>
            {toggle &&(<RegisterForm/>)}
        </div>
        </>
    )
}
export default LoginOrRegister;

and here is the useToggle custom hook.

import { useState } from "react";
const useToggle = (initialState) => {
    const [toggleValue, setToggleValue] = useState(initialState);

    const toggler = () => { setToggleValue(!toggleValue) };
    return [toggleValue, toggler]
  };

  export default useToggle

1

There are 1 best solutions below

0
Salman-13 On

One option is to use a custom useToggle hook on the parent component (which is re-rendered) and pass the data to the child component

const LoginOrRegister = ({toggle, setToggle}) => { ... }