Post

React State

React State

We use state for variables whose value can change over time, and that when changed should trigger the component to re-render with the new data. Essentially, we use state to make our components interactive

  • Changes to the state can only trickle down to child elements they cant move up to parent elements
  • What changes when state change
  • The states can become difficult to manage use the context api which is built into react to help manage state Key to success: decide the state and where it lives
  • State can be an object of properties

setState

  • setState is an asynchronous function call
  • setState has a callback function which solves state not updating correctly due to its asynchronous nature
1
2
3
4
5
6
7
8
9
10
// Wrong
this.state.comment = "Hello";

//Instead, use setState():

// Correct
this.setState({ comment: "Hello" });

//setState with callback function to run after setState
this.setState({ searchField: e.target.value }, () => console.log(this.state));

React State and Components

  • State is declared in one place and trickled down as props for use in child components.
  • Components can have state - like a menu can have an open / close state.
  • You can pass in props which helps to add dynamic values into the content.
  • Sometimes you want to share that state across multiple components - app or global state.
  • Function components allow you to use state through hooks - such as the useState hook.
  • When you call setState in a component the component will rerender

Example: React state lives in a parent component and is passed down to a child as props.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import { useState } from "react";
import Child from "./Child";

function Parent() {
  // Declare a state variable named 'count', and a function to update it 'setCount'
  const [count, setCount] = useState(0);

  return (
    <div>
      <h2>Parent count: {count}</h2>

      <button onClick={() => setCount(count + 1)}>
        Increment
      </button>

      {/* state + updater passed as props */}
      <Child count={count} setCount={setCount} />
    </div>
  );
}

export default Parent;
This post is licensed under CC BY 4.0 by the author.