# State

### What is State?

State serves as a component's memory, allowing it to store and track information between renders.

### The `useState` Hook

The `useState`  hook enables state management in functional components. It accepts an initial value and returns an array containing:

1. The current state value
2. A function to update that value

```tsx
const [currentValue, setValue] = useState(initialVal);

// example:
const [color, setColor] = useState(defaultColor);
```

Note: `useState(initialVal)`  returns an array, `["val", "func"]` destructures the array to access the elements and assign it to a specific name.

### React's Rendering Process

When a component's state or props change, React performs a rerender by:

1. Destroying the current component instance (including all variables and functions)
2. Recreating it with the updated state values

During this process, React maintains state consistency by providing the latest values to the recreated component. The initial value is only used on the first render.

### Implementing State Variables

To add state:

1. Import useState:

```tsx
import { useState } from "React";
```

2. Replace regular variables with state:

```tsx
// Before
let counter = 0;

// After
const [counter, setCounter] = useState(0);
```

3. Update state using a setter function:

```tsx
function increment() {
    setCounter(counter + 1);
}

// or you can declare an arrow/anonymous function, which is more modern
const increment = () => setCounter(counter + 1);
```

### Additional resources:

{% embed url="<https://react.dev/learn/managing-state>" %}

{% embed url="<https://www.w3schools.com/react/react_state.asp>" %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://wiki.nushackers.org/orbital/react/state.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
