Skip to main content

Component State

In React, the component state is an object that holds information that can change and affect the behavior or rendering of a component. The state is managed by the component itself and can be updated using the setState() method.

Here is a basic example of a React component with state:

import React, { useState } from 'react';

function MyComponent() {
const [counter, setCounter] = useState(0);

function handleClick() {
setCounter(counter + 1);
}

return (
<div>
<p>Counter: {counter}</p>
<button onClick={handleClick}>Increment</button>
</div>
);
}

export default MyComponent;

Now as usual, call this component in the parent component.

import MyComponent from './MyComponent';

function App() {
return (
<div>
<MyComponent />
</div>
);
}

In this example, we are using the useState hook to create a state variable called counter with an initial value of 0. We then have a button that, when clicked, will call the handleClick function which will call setCounter to update the counter state variable by 1.

It's important to note that the state should only be updated using the setState() method, and never directly. Updating the state directly will not trigger a re-render and the component will not update.

Another thing to keep in mind is that the state should only be used for values that change within the component, and not for props passed down from a parent component. It's best practice to use props for values that are passed down from a parent component and state for values that are local to the component.

When the state changes, the component will re-render, updating the view to reflect the new state.

In addition to useState, React also provides other hooks such as useEffect and useContext that help manage state and lifecycle in a functional component. But we will get into all that later,