React JS useState hook
1: import React, { useState } from 'react'; 2: 3: function Example() { 4: const [count, setCount] = useState(0); 5: 6: return ( 7:8:13: ); 14: }You clicked {count} times
9: 12:
Line 1: Import the useState Hook from React. It lets us keep local state in a function component.
Line 4: Declare a new state variable by calling the useState Hook. It returns a pair of values, to which we give names. We’re calling our variable count because it holds the number of button clicks. We initialize it to zero by passing 0 as the only useState argument. The second returned item is itself a function. It lets us update the count so we’ll name it setCount.
Line 9: When the user clicks, we call setCount with a new value. React will then re-render the Example component, passing the new count value to it.
const [count, setCount] = useState(0); const [fruit, setFruit] = useState('banana');
– You can call useState multiple times for multiple variables your app needs.
– The square bracket syntax is called array destructuring, useState returns a pair of values. It means that we’re making two new variables fruit and setFruit, where fruit is set to the first value returned by useState, and setFruit is the second. It is equivalent to this code:
var fruitStateVariable = useState('banana'); // Returns a pair var fruit = fruitStateVariable[0]; // First item in a pair var setFruit = fruitStateVariable[1]; // Second item in a pair
Reference:
https://reactjs.org/docs/hooks-state.html
Search within Codexpedia
Search the entire web