• Home
  • React
  • React Hooks – useState hook example

React Hooks – useState hook example



Hooks are a new functionality of React, thanks to which we can “hook into” React features, which makes writing applications easier. First hook that I want to show you is called useState and it is a hook that allows you to use state in a functional component (before hooks you could not use states in functional components, which is why they were called stateless components. Now the name has been changed to functional components).

UseState hook returns a stateful value, and a function to update it:

const [state, setState] = useState(initialState);

This means, that you can set your initial state in state variable, and change it using setState function. State and setState are just names, so you can pick other names, like counter and setCounter. You can use as many useState hooks in one component as you want:

const HookExample = () => {

    // state 1 - Declaring new state variable, called "counter"
    const [counter, setCounter] = useState(0);
    // state 2 - Declaring new state variable, called "string"
    const [string, setString] = useState("Hello Word");
  return (
    <div className="App">
      <p> Counter: {counter} </p>
      <p> String: {string} </p>
      <button onClick={() => setCounter(val => val + 1)} > Add 1 </button>
      <button onClick={() => setString("useState hook is easy :)")} > Change text </button>
    </div>
  );
}

This simple code above shows how you can set and change state.

Click on DEMO to see how useState hook works

You can find this code in repo: https://github.com/love-coding-pl/React-Hooks-Examples/tree/Hook-1-useState

Joanna

Leave a Reply

Your email address will not be published. Required fields are marked *