React hooks

From wikinotes
Revision as of 01:55, 11 December 2022 by Will (talk | contribs) (Created page with "Hooks let you use react state within function components (without classes). = Documentation = <blockquote> {| class="wikitable" |- | available hooks || https://reactjs.org/docs/hooks-reference.html |- | docs || https://reactjs.org/docs/hooks-overview.html |- |} </blockquote><!-- Documentation --> = Example = <blockquote> useState lets you initialize state with a value, and returns a setter. <syntaxhighlight lang="javascript"> // copied from official docs function Exam...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Hooks let you use react state within function components (without classes).

Documentation

available hooks https://reactjs.org/docs/hooks-reference.html
docs https://reactjs.org/docs/hooks-overview.html

Example

useState lets you initialize state with a value, and returns a setter.

// copied from official docs
function Example()
    const [count, setCount] = useState(0)  // initial state of counter is '0', 'setCount' updates it

    return (
      <div>
        <p>
        <button onClick={() =setCount(count + 1)}>
          Click me
        </button>
      </div>
    );
}

useState

const [count, setCount] = useState(0);    // set initial state to '0', 'setCount' is setter
const [name, setName] = useState('alex'); // set initial state to 'alex', 'setName is setter

useEffect

Alternative to component-mounting. It is automatically mounted/unmounted.

function MyComponent() {
    // install side-effect
    useEffect(() => {
        document.title = `You clicked ${count} times`
    });

    return ( ... );
}