State Management

💡 React v16.8.0 introduced a new concept: React Hooks to allow developers to tap into React Component state & lifecycle without the need for the class syntax and directly calling lifecycle methods.

React component lifecycle exists to protect component state. Understanding the lifecycle is key to understanding how you can do things the react way. React component state is not meant to be mutated, it’s meant to be replace with each replacement triggering a new render.

Nowadays, you can manage component state and lifecycle inside your function components via React Hook.

⚠️ React Hooks do not work inside classes

Adding State

The useState Hook allows you to add React state to function components. The function takes in a single argument, the initial value of the state and returns a pair: the current state value and a function to update the state.

// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);

Calling useState declares a “State variable”. In our example above, the variable is called count. Unlike function variables that normally disappears when the functions exits, state variables are preserved by React.

Using Multiple State Variables

You can declare more than one state variable within your function component as follow:

function ExampleWithManyStates() {
  // Declare multiple state variables!
  const [count, setCount] = useState(0);
  const [name, setName] = useState('CodePath');
  const [todos, setTodos] = useState([{ text: 'Learn React' }]);
  // ...

Declaring multiple state variables as a pair of [something, setSomething] gives you more control into reading and updating the state. However, you could still group related data together into a state object, with the caveat that updating the state always replaced the entire object.

Reading the state

When you want to display the current state value, just use the state variable directly:

<p>You clicked **{count}** times</p>

Updating the State

To update the state, you use the second argument returned by useState in any part of your function that needs to update the state value.

<button onClick={() => **setCount(count + 1)**}>
****  Click me

In the example above, once the user clicks the button the setCount() get’s call with the new value. React will then re-render the function component, passing the new count value to it.

Fork me on GitHub