DEV Community

Chris Achinga
Chris Achinga

Posted on • Originally published at chrisdevcode.hashnode.dev on

State Management in React

A state is the current data passed in React components. State management in React enables you to dynamically update data in Components.

This post will take you through creating an initial state and an event to trigger a state update in Reactjs.

Prerequisites:

  • NodeJS Installed
  • Knowledge of React

Source Code and Demo

GitHub Repo Link

Creating A New React App :

# create a new react app
npx create-react-app state-management-demo
# move into the new app's directory
cd state management-demo
# start the app to see if everything is okay
npm start

Enter fullscreen mode Exit fullscreen mode

For the Demo, clean the App.js to have the following:

const App = () => {
  return <div>My React Application</div>
}

export default App

Enter fullscreen mode Exit fullscreen mode

We will create a simple counter button to demonstrate state management.

At the top of the App.js file, import useState:

import { useState } from 'react'

Enter fullscreen mode Exit fullscreen mode

Inside the App() function, we will set our default state, 0. Then once a user clicks a button, the number increases by 1 per click.

const [count, setCount] = useState(0)

Enter fullscreen mode Exit fullscreen mode

We will add a function, that will fire up when the button is clicked:

  const handleClick = () => {
    setCount((count) => {
      return count + 1
    })
  }

Enter fullscreen mode Exit fullscreen mode

Update the return function to the following:

  return (
    <div className='container'>
      <h1>Counter</h1>
      <p>{count}</p>
      <button className='btn btn-outline-secondary' onClick={handleClick}>Click Me!</button>
    </div>
  )

Enter fullscreen mode Exit fullscreen mode

Run the development server and open the browser on port 3000: http://localhost:3000/

Screenshot from 2022-07-09 22-06-26.png

The full code:

Here is a demo:

Conclusion:

We created a component and added a button that shows the number of times it's been clicked, using the useState hook. Cool isn't it?

References:

Top comments (0)