React for Real Dummies #1 - Lifting State Up

React for Real Dummies #1 - Lifting State Up

First Post of the React for Real Dummies Series! Today we understand what it means to lift state up.

Lifting state up is a common practice to make the state (an object that contains information about the component's current situation) available to every component of the our app.

Why do we lift state up?

The flow of information in React is unidirectional: it means that the information can be passed only from a parent (e.g., the main app) to a child (for example a navbar or a form) components. Imagine you have one state in the child component but, at some point, you need to update in the app component: that state won't be available in the app! By moving the state from the child to the parent component, we make it available to all the child components.

NB: Lifting state up from child to parent is a workaround through which, instead passing state from child to parent, we 1) move the state up to the parent and 2) we pass the data in the state down to the child by using props. It is possible to pass state from child to parent using callback functions (I will soon write another post of the series about this). The most widely used way to pass data between components is Redux. "The Redux store is the main, central bucket which stores all the states of an application. It should be considered and maintained as a single source of truth for the state of the application", Freecodecamp writes.

How do we lift state up?

To interactively follow along, you can open this Scrim.

We have two components, an App (parent component) and a Child. First, the state is moved from the Child to the App. Then, using the syntax of HTML attributes (they are not, though!) we specify the name of the props of the child. 'name' and 'surname' are indeed props! To the right of the props, in curly brackets (as we are entering JSX) we specify the value of the prop.

import React from "react"
import Child from "./Child.js"

export default function App () {


    const [playerName, setPlayerName] = React.useState({name: "Romelu", surname: "Lukaku"})

    return (
        <div>
            <Child name={playerName.name} surname={playerName.surname} />
        </div>
    )}

Now, in the Child component, we can pass the props: JSX will already know that there are two props for the Child, name and surname. In the Child component now we can call the props (name and surname) whenever we need to use the name or surname of the player.

import React from "react"

export default function Child (props) {

    return (

        <main>
            <p>Name: {props.name} {props.surname}</p>   
        </main>
    )}

I hope this helped you!

Until next time!

P.s. I support Inter Milan and Romelu is one of my favorite players!