DEV Community

Douglas Henrique
Douglas Henrique

Posted on

React state explained

React state explained

State is a runtime data that react relies upon in order to render your app. This data changes over time and typically affects the visual output of our app.

There is an example of how to use:

Import the useState

import { useState } from 'react'
Enter fullscreen mode Exit fullscreen mode

Declare the state inside of your component

import { useState } from 'react'

const SomeComponent = () => { 
    const [name, setName] = useState('')

    return (
    <div>
        {name}
        <button onClick={() => setName('doug')}> Change name </button>
    </div>
    )
}

export { SomeComponent } 

Enter fullscreen mode Exit fullscreen mode

So, as we can see, we have 2 properties returned by the useState hook:

**name: returns the state value

**setName: function to set the state value

When setName is called, react re-render the app updating the name state with the new value.

Additional info (important)

There is another type of data that changes over time and makes part of our application but not of react state like mouse position, scroll position and others. The browser keeps track of this data but because doesn't live inside of react or trigger re-renders of our application, this is not React state.

Top comments (0)