React Function Component - State (useState Hook)


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


With the React.useState hook


With the createElement

  • The component
function Example(props) {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = React.useState(0);
  return React.createElement(
      React.createElement("p", null, props.user, " clicked ", count, " times"),
      React.createElement("button", { onClick: () => setCount(count + 1) } , "Click Me")
  • The rendering part
    React.createElement(Example, { user: "Foo"}), 
  • Result:


React - JSX

  • The component
function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = React.useState(0);

  return (
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
  • The rendering part
  • Result:



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

const { currentValue, setValue } = useState(initialState);
// or
[<getter>, <setter>] = useState(<initialValue>)


  • 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.


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.

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.

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

Documentation / Reference

Powered by ComboStrap