What is the useState Hook and how to use it? Local State in a React Function Component

About

This page is about the local state (known as the state in react) in a React Functional Component.

In this context, the state is managed by the useState hook.

Example

The local state in React is managed with the React.useState hook

Native

With the createElement

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

Jsx

An example written in React - JSX.

  • The component
function Counter() {
  // 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
ReactDOM.render(
    <Counter/>,
    document.getElementById('root')
);
  • Result:

Important: State does not persist on component Mount

This Jsx example shows you that the local state does not persist between mount (ie rendering).

We:

  • Use the same previous counter example
  • and show or cache it (mount/demount) via a button

Example:

function App(){
  
  const [show, setShow] = React.useState(1);
  
  let counter;
  if(show){
     counter = <Counter/>;
  }
  
  return (
    <div>
      <button onClick={()=>setShow(!show)}>{show? 'Demount the counter' : 'Mount the counter'}</button>
      {counter}
    </div>
  ); 
}
  • Result:
    • Click on the counter button to increment the counter,
    • Cache the counter and show it again with the mount button
    • You will see that the counter is back to 0

Syntax

Single

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>)

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 is a function that lets you update the value and trigger a render. It accepts:
      • a single value
      • a function where the first argument is the previous state

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.

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

1)





Discover More
How to inject multi React components in a page? A Multiple Root demo

This page shows how to render multiple root in the same web page For instance, when you want to integrate React component in another HTML application (php, ruby,...) with templating, you may render several...
React - Component (User-defined Element)

A component is a user-defined react element in the React tree. Components let you split the UI into independent, reusable pieces, and think each piece in isolation. Conceptually, components are like...
React - How to persist the local state between rendering without any library? (custom useState Hook)

This article shows you how to persist your local state (ie React state) between re-render without the use of any state library We will use the classic React counter. If you refresh the page or unmount...
React - Local component state (known as State)

This page is the local state of a component. In React, this local state is known as state A change of value triggers a rendering State is useful for handling data that is local to the component...
React - Rendering (Lifecycle)

This page is rendering in React (ie update of the DOM) To make the UI interactive, you need to be able to trigger changes to your underlying data model. The root element is the element passed to...
React - State

This page is UI State in React. The Local state to a component in react is known as: state. A change of state triggers a render ref. A change of ref value does not triggers a render The global...
React Hook Side Effect Doc Title
React Function Component - (Side) Effect (useEffect Hook)

Effect Hook is a hook that lets you perform side effects in functional components, and is similar to lifecycle methods in classes. An effect is also known as a side-effect Example of effect: Data...
What are React Hooks?

hooks are functions that: let you hook into React state and lifecycle features from function components. can be used only in a functional component (ie not inside classes component) may call other...
What is React useEffect?

useEffectuseEffect is an effect that: is asynchronous and executes at the end of the rendering. Specifically, it runs at the end of a commit after the screen updates, after every render When...



Share this page:
Follow us:
Task Runner