স্টেট: কম্পোনেন্ট এর মেমোরি
ইন্টারেকশনের ফলে প্রায়ই কম্পোনেন্ট কে প্রায়ই স্ক্রিনে যা আছে তা পরিবর্তন করতে হয়। ফর্মে টাইপ করলে ইনপুট ফিল্ড আপডেট হয়ে যাওয়া উচিত, ইমেজ ক্যারাউজেলে এর “next” এ ক্লিক করলে ডিসপ্লের ইমেজ চেঞ্জ হওয়া উচিত, “buy” এ ক্লিক করলে প্রোডাক্ট শপিং কার্ট এ যাওয়া উচিত। কম্পোনেন্ট এর কিছু জিনিস মনে রাখা উচিত, যেমন: বর্তমান ইনপুট ভেলু, বর্তমান ইমেজ, শপিং কার্ট। রিয়েক্ট এর কম্পোনেন্ট এরকম কম্পোনেন্ট-ভিত্তিক মেমোরি কে state বলে।
আপনি যা শিখবেন
useState
দিয়ে কিভাবে একটি স্টেট ভেরিয়েবল তৈরি করা যায়useState
হুক কোন দুইটি ভেরিয়েবল রিটার্ন করে- কিভাবে একাধিক স্টেট ভেরিবল তৈরি করতে হয়
- স্টেট কে কেন লোকাল বলা হয়
যখন রেগুলার ভেরিয়েবল যথেষ্ট নয়
নিচের কম্পোনেন্টটি একটি ভাস্কর্যের ছবি প্রদর্শন করে। “Next” বাটন এ ক্লিক করলে index
এর ভেলু 1
, এরপর 2
এবং এভাবে পরিবর্তন হয়ে পরের ভাস্কর্যের ছবি দেখানো উচিত। কিন্তু, এটা কাজ করবেনা (আপনি চেষ্টা করে দেখতে পারেন!):
import { sculptureList } from './data.js'; export default function Gallery() { let index = 0; function handleClick() { index = index + 1; } let sculpture = sculptureList[index]; return ( <> <button onClick={handleClick}> Next </button> <h2> <i>{sculpture.name} </i> by {sculpture.artist} </h2> <h3> ({index + 1} of {sculptureList.length}) </h3> <img src={sculpture.url} alt={sculpture.alt} /> <p> {sculpture.description} </p> </> ); }
handleClick
ইভেন্ট হ্যান্ডলারটি লোকাল ভেরিয়েবল index
কে আপডেট করছে। তবে, দুটি বিষয় এই পরিবর্তন দেখতে বাধা তৈরি করছে।
- লোকাল ভেরিবলগুলো রেন্ডারগুলির মধ্যে স্থায়ী হয় না। যখন React কোন কম্পোনেন্ট দ্বিতীয়বার রেন্ডার করে, তখন এটি সম্পূর্ণরূপে নতুন করে রেন্ডার করে—এটি লোকাল ভেরিয়েবলগুলিতে কোনও পরিবর্তন বিবেচনা করে না।
- লোকাল ভেরিয়েবলগুলিতে পরিবর্তন রেন্ডারগুলি ট্রিগার করে না। রিয়েক্ট কম্পোনেন্ট নতুন ডেটা দিয়ে রেন্ডার করার প্রয়োজন বুঝতে পারে না।
একটি কম্পোনেন্টকে নতুন ডেটা দিয়ে আপডেট করতে, দুটি বিষয় হতে হবে:
- রেন্ডার এর মধ্যে ডাটা Retain করা।
- রিয়েক্ট কে Trigger করা,কম্পোনেন্টকে নতুন ডাটা দিয়ে রেন্ডার করতে। (রি-রেন্ডারিং).
useState
হুক আপনাকে নিচের দুটি জিনিস দেয়:
- একটি স্টেট ভেরিয়েবল যা রি-রেন্ডারের মধ্যে ডাটা মনে রাখে।
- একটি স্টেট setter ফাংশন যা দিয়ে ভেরিয়েবল আপডেট করা যায় এবং রিয়েক্ট কে ট্রিগার করে কম্পোনেন্টকে আবার রেন্ডার করতে।
স্টেট ভেরিয়েবল তৈরি করা
স্টেট ভেরিয়েবল তৈরি করতে হলে,রিয়েক্ট থেকে ফাইলের উপরে useState
ইমপোর্ট করতে হবে :
import { useState } from 'react';
এরপর, নিচের লাইন টা পরিবর্তন করে:
let index = 0;
নিচের মতো করে নিন
const [index, setIndex] = useState(0);
index
একটি স্টেট ভেরিয়েবল এবং setIndex
হচ্ছে setter ফাংশন।
The
[
and]
syntax here is called array destructuring and it lets you read values from an array. The array returned byuseState
always has exactly two items.
এইভাবে তারা handleClick
এ একসাথে কাজ করে :
function handleClick() {
setIndex(index + 1);
}
এখন “Next” বাটনে ক্লিক করলে বর্তমান ভাস্কর্যটি পরিবর্তন হয়:
import { useState } from 'react'; import { sculptureList } from './data.js'; export default function Gallery() { const [index, setIndex] = useState(0); function handleClick() { setIndex(index + 1); } let sculpture = sculptureList[index]; return ( <> <button onClick={handleClick}> Next </button> <h2> <i>{sculpture.name} </i> by {sculpture.artist} </h2> <h3> ({index + 1} of {sculptureList.length}) </h3> <img src={sculpture.url} alt={sculpture.alt} /> <p> {sculpture.description} </p> </> ); }
আপনার প্রথম হুকের সাথে পরিচয়
রিয়েক্ট এ, useState
, এবং অন্য যেকোনো ফাংশন যার শুরু ”use
” দিয়ে তাদেরকে হুক বলা হয়।
Hooks are special functions that are only available while React is rendering (which we’ll get into in more detail on the next page). They let you “hook into” different React features.
State is just one of those features, but you will meet the other Hooks later.
Anatomy of useState
When you call useState
, you are telling React that you want this component to remember something:
const [index, setIndex] = useState(0);
এই ক্ষেত্রে আপনি চাচ্ছেন রিয়েক্ট index
টি মনে রাখুক.
The only argument to useState
is the initial value of your state variable. In this example, the index
’s initial value is set to 0
with useState(0)
.
Every time your component renders, useState
gives you an array containing two values:
- The state variable (
index
) with the value you stored. - The state setter function (
setIndex
) which can update the state variable and trigger React to render the component again.
Here’s how that happens in action:
const [index, setIndex] = useState(0);
- Your component renders the first time. Because you passed
0
touseState
as the initial value forindex
, it will return[0, setIndex]
. React remembers0
is the latest state value. - You update the state. When a user clicks the button, it calls
setIndex(index + 1)
.index
is0
, so it’ssetIndex(1)
. This tells React to rememberindex
is1
now and triggers another render. - Your component’s second render. React still sees
useState(0)
, but because React remembers that you setindex
to1
, it returns[1, setIndex]
instead. - And so on!
কম্পোনেন্ট এ একাধিক স্টেট ভেরিয়েবল ব্যবহার করা
একটি কম্পোনেন্ট এ আপনি যত খুশি তত ধরনের ষ্টেট ভেরিয়েবল রাখতে পারেন। এই কম্পোনেন্ট এর দুটি স্টেট ভেরিয়েবল আছে, একটি নাম্বার index
এবং একটি বুলিয়ান showMore
যা Toggle করা হয় যখন আপনি “Show details” এ ক্লিক করেন :
import { useState } from 'react'; import { sculptureList } from './data.js'; export default function Gallery() { const [index, setIndex] = useState(0); const [showMore, setShowMore] = useState(false); function handleNextClick() { setIndex(index + 1); } function handleMoreClick() { setShowMore(!showMore); } let sculpture = sculptureList[index]; return ( <> <button onClick={handleNextClick}> Next </button> <h2> <i>{sculpture.name} </i> by {sculpture.artist} </h2> <h3> ({index + 1} of {sculptureList.length}) </h3> <button onClick={handleMoreClick}> {showMore ? 'Hide' : 'Show'} details </button> {showMore && <p>{sculpture.description}</p>} <img src={sculpture.url} alt={sculpture.alt} /> </> ); }
It is a good idea to have multiple state variables if their state is unrelated, like index
and showMore
in this example. But if you find that you often change two state variables together, it might be easier to combine them into one. For example, if you have a form with many fields, it’s more convenient to have a single state variable that holds an object than state variable per field. Read Choosing the State Structure for more tips.
Deep Dive
You might have noticed that the useState
call does not receive any information about which state variable it refers to. There is no “identifier” that is passed to useState
, so how does it know which of the state variables to return? Does it rely on some magic like parsing your functions? The answer is no.
Instead, to enable their concise syntax, Hooks rely on a stable call order on every render of the same component. This works well in practice because if you follow the rule above (“only call Hooks at the top level”), Hooks will always be called in the same order. Additionally, a linter plugin catches most mistakes.
Internally, React holds an array of state pairs for every component. It also maintains the current pair index, which is set to 0
before rendering. Each time you call useState
, React gives you the next state pair and increments the index. You can read more about this mechanism in React Hooks: Not Magic, Just Arrays.
This example doesn’t use React but it gives you an idea of how useState
works internally:
let componentHooks = []; let currentHookIndex = 0; // How useState works inside React (simplified). function useState(initialState) { let pair = componentHooks[currentHookIndex]; if (pair) { // This is not the first render, // so the state pair already exists. // Return it and prepare for next Hook call. currentHookIndex++; return pair; } // This is the first time we're rendering, // so create a state pair and store it. pair = [initialState, setState]; function setState(nextState) { // When the user requests a state change, // put the new value into the pair. pair[0] = nextState; updateDOM(); } // Store the pair for future renders // and prepare for the next Hook call. componentHooks[currentHookIndex] = pair; currentHookIndex++; return pair; } function Gallery() { // Each useState() call will get the next pair. const [index, setIndex] = useState(0); const [showMore, setShowMore] = useState(false); function handleNextClick() { setIndex(index + 1); } function handleMoreClick() { setShowMore(!showMore); } let sculpture = sculptureList[index]; // This example doesn't use React, so // return an output object instead of JSX. return { onNextClick: handleNextClick, onMoreClick: handleMoreClick, header: `${sculpture.name} by ${sculpture.artist}`, counter: `${index + 1} of ${sculptureList.length}`, more: `${showMore ? 'Hide' : 'Show'} details`, description: showMore ? sculpture.description : null, imageSrc: sculpture.url, imageAlt: sculpture.alt }; } function updateDOM() { // Reset the current Hook index // before rendering the component. currentHookIndex = 0; let output = Gallery(); // Update the DOM to match the output. // This is the part React does for you. nextButton.onclick = output.onNextClick; header.textContent = output.header; moreButton.onclick = output.onMoreClick; moreButton.textContent = output.more; image.src = output.imageSrc; image.alt = output.imageAlt; if (output.description !== null) { description.textContent = output.description; description.style.display = ''; } else { description.style.display = 'none'; } } let nextButton = document.getElementById('nextButton'); let header = document.getElementById('header'); let moreButton = document.getElementById('moreButton'); let description = document.getElementById('description'); let image = document.getElementById('image'); let sculptureList = [{ name: 'Homenaje a la Neurocirugía', artist: 'Marta Colvin Andrade', description: 'Although Colvin is predominantly known for abstract themes that allude to pre-Hispanic symbols, this gigantic sculpture, an homage to neurosurgery, is one of her most recognizable public art pieces.', url: 'https://i.imgur.com/Mx7dA2Y.jpg', alt: 'A bronze statue of two crossed hands delicately holding a human brain in their fingertips.' }, { name: 'Floralis Genérica', artist: 'Eduardo Catalano', description: 'This enormous (75 ft. or 23m) silver flower is located in Buenos Aires. It is designed to move, closing its petals in the evening or when strong winds blow and opening them in the morning.', url: 'https://i.imgur.com/ZF6s192m.jpg', alt: 'A gigantic metallic flower sculpture with reflective mirror-like petals and strong stamens.' }, { name: 'Eternal Presence', artist: 'John Woodrow Wilson', description: 'Wilson was known for his preoccupation with equality, social justice, as well as the essential and spiritual qualities of humankind. This massive (7ft. or 2,13m) bronze represents what he described as "a symbolic Black presence infused with a sense of universal humanity."', url: 'https://i.imgur.com/aTtVpES.jpg', alt: 'The sculpture depicting a human head seems ever-present and solemn. It radiates calm and serenity.' }, { name: 'Moai', artist: 'Unknown Artist', description: 'Located on the Easter Island, there are 1,000 moai, or extant monumental statues, created by the early Rapa Nui people, which some believe represented deified ancestors.', url: 'https://i.imgur.com/RCwLEoQm.jpg', alt: 'Three monumental stone busts with the heads that are disproportionately large with somber faces.' }, { name: 'Blue Nana', artist: 'Niki de Saint Phalle', description: 'The Nanas are triumphant creatures, symbols of femininity and maternity. Initially, Saint Phalle used fabric and found objects for the Nanas, and later on introduced polyester to achieve a more vibrant effect.', url: 'https://i.imgur.com/Sd1AgUOm.jpg', alt: 'A large mosaic sculpture of a whimsical dancing female figure in a colorful costume emanating joy.' }, { name: 'Ultimate Form', artist: 'Barbara Hepworth', description: 'This abstract bronze sculpture is a part of The Family of Man series located at Yorkshire Sculpture Park. Hepworth chose not to create literal representations of the world but developed abstract forms inspired by people and landscapes.', url: 'https://i.imgur.com/2heNQDcm.jpg', alt: 'A tall sculpture made of three elements stacked on each other reminding of a human figure.' }, { name: 'Cavaliere', artist: 'Lamidi Olonade Fakeye', description: "Descended from four generations of woodcarvers, Fakeye's work blended traditional and contemporary Yoruba themes.", url: 'https://i.imgur.com/wIdGuZwm.png', alt: 'An intricate wood sculpture of a warrior with a focused face on a horse adorned with patterns.' }, { name: 'Big Bellies', artist: 'Alina Szapocznikow', description: "Szapocznikow is known for her sculptures of the fragmented body as a metaphor for the fragility and impermanence of youth and beauty. This sculpture depicts two very realistic large bellies stacked on top of each other, each around five feet (1,5m) tall.", url: 'https://i.imgur.com/AlHTAdDm.jpg', alt: 'The sculpture reminds a cascade of folds, quite different from bellies in classical sculptures.' }, { name: 'Terracotta Army', artist: 'Unknown Artist', description: 'The Terracotta Army is a collection of terracotta sculptures depicting the armies of Qin Shi Huang, the first Emperor of China. The army consisted of more than 8,000 soldiers, 130 chariots with 520 horses, and 150 cavalry horses.', url: 'https://i.imgur.com/HMFmH6m.jpg', alt: '12 terracotta sculptures of solemn warriors, each with a unique facial expression and armor.' }, { name: 'Lunar Landscape', artist: 'Louise Nevelson', description: 'Nevelson was known for scavenging objects from New York City debris, which she would later assemble into monumental constructions. In this one, she used disparate parts like a bedpost, juggling pin, and seat fragment, nailing and gluing them into boxes that reflect the influence of Cubism’s geometric abstraction of space and form.', url: 'https://i.imgur.com/rN7hY6om.jpg', alt: 'A black matte sculpture where the individual elements are initially indistinguishable.' }, { name: 'Aureole', artist: 'Ranjani Shettar', description: 'Shettar merges the traditional and the modern, the natural and the industrial. Her art focuses on the relationship between man and nature. Her work was described as compelling both abstractly and figuratively, gravity defying, and a "fine synthesis of unlikely materials."', url: 'https://i.imgur.com/okTpbHhm.jpg', alt: 'A pale wire-like sculpture mounted on concrete wall and descending on the floor. It appears light.' }, { name: 'Hippos', artist: 'Taipei Zoo', description: 'The Taipei Zoo commissioned a Hippo Square featuring submerged hippos at play.', url: 'https://i.imgur.com/6o5Vuyu.jpg', alt: 'A group of bronze hippo sculptures emerging from the sett sidewalk as if they were swimming.' }]; // Make UI match the initial state. updateDOM();
You don’t have to understand it to use React, but you might find this a helpful mental model.
State is isolated and private
State is local to a component instance on the screen. In other words, if you render the same component twice, each copy will have completely isolated state! Changing one of them will not affect the other.
In this example, the Gallery
component from earlier is rendered twice with no changes to its logic. Try clicking the buttons inside each of the galleries. Notice that their state is independent:
import Gallery from './Gallery.js'; export default function Page() { return ( <div className="Page"> <Gallery /> <Gallery /> </div> ); }
This is what makes state different from regular variables that you might declare at the top of your module. State is not tied to a particular function call or a place in the code, but it’s “local” to the specific place on the screen. You rendered two <Gallery />
components, so their state is stored separately.
Also notice how the Page
component doesn’t “know” anything about the Gallery
state or even whether it has any. Unlike props, state is fully private to the component declaring it. The parent component can’t change it. This lets you add state to any component or remove it without impacting the rest of the components.
What if you wanted both galleries to keep their states in sync? The right way to do it in React is to remove state from child components and add it to their closest shared parent. The next few pages will focus on organizing state of a single component, but we will return to this topic in Sharing State Between Components.
Recap
- Use a state variable when a component needs to “remember” some information between renders.
- State variables are declared by calling the
useState
Hook. - Hooks are special functions that start with
use
. They let you “hook into” React features like state. - Hooks might remind you of imports: they need to be called unconditionally. Calling Hooks, including
useState
, is only valid at the top level of a component or another Hook. - The
useState
Hook returns a pair of values: the current state and the function to update it. - You can have more than one state variable. Internally, React matches them up by their order.
- State is private to the component. If you render it in two places, each copy gets its own state.
Challenge 1 of 4: গ্যালারিটি সম্পূর্ণ করুণ
When you press “Next” on the last sculpture, the code crashes. Fix the logic to prevent the crash. You may do this by adding extra logic to event handler or by disabling the button when the action is not possible.
After fixing the crash, add a “Previous” button that shows the previous sculpture. It shouldn’t crash on the first sculpture.
import { useState } from 'react'; import { sculptureList } from './data.js'; export default function Gallery() { const [index, setIndex] = useState(0); const [showMore, setShowMore] = useState(false); function handleNextClick() { setIndex(index + 1); } function handleMoreClick() { setShowMore(!showMore); } let sculpture = sculptureList[index]; return ( <> <button onClick={handleNextClick}> Next </button> <h2> <i>{sculpture.name} </i> by {sculpture.artist} </h2> <h3> ({index + 1} of {sculptureList.length}) </h3> <button onClick={handleMoreClick}> {showMore ? 'Hide' : 'Show'} details </button> {showMore && <p>{sculpture.description}</p>} <img src={sculpture.url} alt={sculpture.alt} /> </> ); }