← 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. c52b973 Harnessing the Power of useRef Hook in React

    tag: reacttag: hookstag: useRef

  2. 8150376 Adding Event Handlers in JSX

    tag: reacttag: jsxtag: event handlers

  3. 2c098c3 Avoiding Unnecessary Re-renders with React.memo

    tag: reacttag: web developmenttag: performance optimization

  4. c2ffa3b Optimizing React Apps with useCallback

    tag: reacttag: useCallbacktag: optimization

00:00

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

Can you stay a bit longer?