🎁 The Js-Craft Guide to React is now available with a 30% off discount!

React useState() – primitives vs objects in component rendering

When working with the useState() hook in React it's important to keep in mind how Javascript manages primitive and object values.

For example, let's first create a component that puts a constant primitive number in the state:

const WithPrimitive = ()=> {
    const [primVal, setPrimVal] = useState(1)
    const handleClick = () => setPrimVal(1)
    console.log('Re-rendering 🗿 WithPrimitive')
    return <div className='comp'>
        <h1>🗿 Primitive val: {primVal}</h1>
        <button onClick={handleClick}>
            State value to 1
        </button>
    </div>
} 

Next, let's also create another one that stores a constant object value in the state:

const WithObject = ()=> {
    const [objVal, setObjVal] = useState({name: 'foo'})
    const handleClick = () => setObjVal({name: 'foo'})
    console.log('Re-rendering 📦 WithObject')
    return <div className='comp'>
        <h1>📦 Object val: {JSON.stringify(objVal)}</h1>
        <button onClick={handleClick}>
            State value to {JSON.stringify({name: 'foo'})}
        </button>
    </div>
} 

You will notice that each time we press the State value to {name: 'foo'} button we will get in the console the Re-rendering 📦 WithObject message while clicking the State value to 1 button will not re-render its component.
React useState() - primitives vs objects in component rerendering

Even if both components put constant values in the setState() hook one rerenders while the other does not.

This is because of how Javascript handles primitive values vs object references. For Javascript 1===1, while {name: 'foo'} is not the same as another {name: 'foo'}:

const [val, setVal] = useState({name: 'foo'})
const handleClick = () => setVal({name: 'foo'})
// this will rerender the component
// because {name: 'foo'} != {name: 'foo'}

// while...

const [val, setVal] = useState(1)
const handleClick = () => setVal(1)
// will not trigger a rerender 
// because 1 == 1

The same will happen if we have booleans or strings instead of numbers. The component will not be rerendered as the state does not change.

While for objects, even if the content of the objects is identical their references are different, therefore the state changes so we get a rerender.

So keep this in mind to avoid unnecessary re-renders.

You can check out the full code here and the running example here.

By the way in this example, I've just done a console.log() to signal the rendering but you can also use the useRef() hook for a better counting of the rerenders.

10 Javascript AI projects with Langchain & React

Not sure what to build? Dive in with these Javascript AI projects! Learn how to build LLM powered apps using Langchain.js and React! Connect your apps to LLMs such as OpenAI, create agents, use vector databases, or setup AI context.

10 Javascript AI projects with Langchain & React

Not sure what to build? Dive in with these Javascript AI projects! Learn how to build LLM powered apps using Langchain.js and React! Connect your apps to LLMs such as OpenAI, create agents, use vector databases, or setup AI context.


Leave a Reply

Your email address will not be published. Required fields are marked *

📘 The Guide to React Home Screencasts Best of Newsletter Search X

📘 - 10 Javascript AI projects with React and LangChain

Hi friend! Before you go, just wanted to let you know about the 10 Javascript AI projects ideas with React and LangChain FREE ebook.

One of the best ways to learn is by doing the work. Choose from these 10 project ideas and start working on topics such as:

  • How does LangChain work
  • Connecting to OpenAI LLM
  • Create AI Agents
  • Simple and Sequential Chains
  • Adding Memory (Chat Context)
  • Prompt Templates
  • Using OutputParsers and Tools for Agents
  • Work with Documents and more...

Keep building and see the new capabilities LLM models can add to your React app! Get all projects as an ebook right to your inbox!

X