React Function Component - State (useState Hook)

> (World Wide) Web - (W3|WWW) > Javascript (Js|ECMAScript) > React > Function Component

1 - About

state in a React Functional Component is managed by the useState hook

Advertising

3 - Example

With the React.useState hook

  • The component
example.js
function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = React.useState(0);
 
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
  • The rendering part
example.js
ReactDOM.render(
    <Example/>,
    document.getElementById('root')
);
  • The root element where React will render
index.html
<div id="root"></div>

4 - Syntax

4.1 - Single

Normally, variables “disappear” when the function exits but React will preserve the state between re-renders.

const { currentValue, setValue } = useState(initialState);

where:

  • initialState is:
    • the only useStateargument and define the initial state.
    • only used during the first render.
  • useState returns a pair:
    • currentValue, the current state value
    • setValue a function that:
      • lets you update the value.
      • you can call from an event handler or somewhere else.
Advertising

4.2 - Multiple

Declaring multiple state variables is just a question of copying the declaration line

const [age, setAge] = useState(42);
const [fruit, setFruit] = useState('banana');
const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);

There is no use of name for state identification, the order is then important ! React assumes that if you call useState many times, you do it in the same order during every render.

4.2.1 - How multiple useState() calls each get independent local state ?

React keeps track:

  • of the currently rendering component.
  • of the state with an an internal list of “memory cells” (object) (associated with each component).

When you call a Hook like useState(), it:

  • reads the current component
  • reads or create a component cell
  • moves the pointer to the next cell.

5 - useState versus setState

It’s similar to this.setState in a class, except:

  • it doesn’t merge the old and new state together.
  • updating a state variable always replaces it instead of merging it.
  • the state doesn’t have to be an object
Advertising

6 - Documentation / Reference