0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

propsに渡すオブジェクトはmemo化しなければならない(戒め)

Last updated at Posted at 2021-12-22

はじめに

不要なレンダリングを回避するための備忘録です。

よくないやりかた

NameListのpropsにオブジェクトを直で渡してしまうと、someOtherStateが変化するたびにNameListが再レンダーされてしまう。

NameList.tsx
...
export const NameList: React.FC<string[]> = ({names}) => {
 return (
  <>
   {names.map((name, key) => (<div key={key}> {name} </div>))}
  </>
 )
} 
Users.tsx
...
interface IUser {
 name: string;
 id: number;
}

const Users: React.FC<> = () => {
 const [users,setUsers] = useState<IUser[]>(initialUsers)
 const [someOtherState, setSomeOtherState] = useState<ISomething>(initialSomething)

 return ( <NameList names={users.map(user => user.name)}> )
}

正しいやり方

NameListのpropsに渡すオブジェクトをmemo化する。そうすればsomeOtherStateが変化してもNameListは再レンダーされない。

NameList.tsx
...
export const NameList: React.FC<string[]> = ({names}) => {
 return (
  <>
   {names.map((name, key) => (<div key={key}> {name} </div>))}
  </>
 )
} 
Users.tsx
...
interface IUser {
 name: string;
 id: number;
}

const Users: React.FC<> = () => {
 const [users,setUsers] = useState<IUser[]>(initialUsers)
 const [someOtherState, setSomeOtherState] = useState<ISomething>(initialSomething)
 
 // ここ!!
 const names = useMemo(() => users.map(user => user.name), [users])

 return ( <NameList names={names}> )
}
0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?