Padi
Padi

Reputation: 801

how to reset react hooks state?

I'm a little bit new to react, I read this doc about hooks and I have a popover with Show More option. The show more function need to show an extra text when it clicked and hide after popover is gone.

the popover function is:

export default function Popover(props) {

  const [viewDetails, setViewDetails] = useState(false);

  return (
    <div>
          <h5>{props.title}</h5>

          {viewDetails ?
            'yes, more details here ...' : 'no'}

          <span onClick={() => {setViewDetails(!viewDetails); console.log(viewDetails)}}>Show more</span>

    </div>
  );
}

and I need a simple local variable which will have 'the state' only when the popover is active.

Why I can't do something like:

export default function Popover(props) {

      let viewDetails = false;

      return (
        <div>
              <h5>{props.title}</h5>

              {viewDetails ?
                'yes, more details here ...' : 'no'}

              <span onClick={() => {viewDetails = !viewDetails; console.log(viewDetails)}}>Show more</span>

        </div>
      );
    }

? I see that the value is always false when the popover is shown and I can set it to true on click but the {viewDetails ? 'yes, more details here ...' : 'no'} doesn't change

Upvotes: 0

Views: 7383

Answers (1)

Joseph D.
Joseph D.

Reputation: 12174

A variable which is not a state variable can not cause a re-render.

You can solve this via lifting state up.

Move how you set the view to the parent component.

function Details(props) {
  return (
    <div>
      <h5>{props.title}</h5>
      <span>{props.details}</span>
    </div>
  );
}

function Popover(props) {
  const [view, setView] = useState(false);

  return (
    <>
      { view && <Details details={props.details} /> }
      <span onClick={() => setView(!view)}>
        Show { view ? 'less': 'more' }
      </span>
    </>
  );
}

Upvotes: 1

Related Questions