← react hacks / react / setting-initial-state-with-usestate.md

Setting Initial State with React's useState Hook

Learn how to set initial state in React using useState hook. This post includes snippets of code for a better understanding.

When using React, it’s often necessary to set an initial state for your components. This can be achieved using the useState hook.

Here’s how you can set the initial state:

import React, { useState } from 'react';

function App() {
  const [state, setState] = useState('Initial State');

  return (
    <div>
      <p>{state}</p>
    </div>
  );
}

export default App;

In the above example, useState hook is called with the initial state ‘Initial State’. It returns a pair - the current state value (state in our case) and a function that lets you update it (setState).

The useState hook is a built-in function in React that lets you add and manipulate state in functional components. This was not possible in earlier versions of React without converting the functional component into a class component.

Keep experimenting!

Quick hacks and tips from my daily workflow. Found this useful? Let me know.

@samuellawrentz →

$ ls ../react | head -4

More hacks

cd ../react →
  1. 3450e43 Enhancing Your Coding Experience with Neovim: A Beginner’s Guide

    tag: neovimtag: codingtag: productivity

  2. 9676c32 Understanding Neovim: How to Customize and Improve Your Text Editor

    tag: neovimtag: text-editortag: customization

  3. c52b973 Harnessing the Power of useRef Hook in React

    tag: reacttag: hookstag: useRef

  4. 8150376 Adding Event Handlers in JSX

    tag: reacttag: jsxtag: event handlers

00:00

This helps me increase the session time of my site. Thank you!

Can you stay a bit longer?