← React Beginner Questions - Set 2 Q13

What is the purpose of the useState hook?

React Beginner Questions - Set 2

It gives a function component a piece of memory between renders, plus a setter that schedules a re-render.

Example

import { useState } from 'react';

export default function Profile() {
  const [name, setName] = useState('Ana');
  const [visible, setVisible] = useState(true);

  return (
    <section>
      <button onClick={() => setVisible(v => !v)}>
        {visible ? 'Hide' : 'Show'} details
      </button>

      {visible && (
        <input value={name} onChange={e => setName(e.target.value)} />
      )}
    </section>
  );
}

What to notice

← Back to the question list