React hooks: Difference between revisions
From wikinotes
(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...") |
|||
Line 43: | Line 43: | ||
= useEffect = | = useEffect = | ||
<blockquote> | <blockquote> | ||
Alternative to component-mounting. It is automatically mounted/unmounted. | Alternative to component-mounting. It is automatically mounted/unmounted.<br> | ||
By default, it runs every time <code>render()</code> is called. | |||
<syntaxhighlight lang="javascript"> | <syntaxhighlight lang="javascript"> |
Latest revision as of 22:40, 15 February 2024
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.
By default, it runs every timerender()
is called.function MyComponent() { // install side-effect useEffect(() => { document.title = `You clicked ${count} times` }); return ( ... ); }